10

Type assertions and type switches

 3 years ago
source link: https://yourbasic.org/golang/type-assertion-switch/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Type assertions and type switches

yourbasic.org/golang

A type assertion provides access to an interface’s concrete value.

Type assertions

A type assertion doesn’t really convert an interface to another data type, but it provides access to an interface’s concrete value, which is typically what you want.

The type assertion x.(T) asserts that the concrete value stored in x is of type T, and that x is not nil.

  • If T is not an interface, it asserts that the dynamic type of x is identical to T.
  • If T is an interface, it asserts that the dynamic type of x implements T.
var x interface{} = "foo"

var s string = x.(string)
fmt.Println(s)     // "foo"

s, ok := x.(string)
fmt.Println(s, ok) // "foo true"

n, ok := x.(int)
fmt.Println(n, ok) // "0 false"

n = x.(int)        // ILLEGAL
panic: interface conversion: interface {} is string, not int

Type switches

A type switch performs several type assertions in series and runs the first case with a matching type.

var x interface{} = "foo"

switch v := x.(type) {
case nil:
    fmt.Println("x is nil")            // here v has type interface{}
case int: 
    fmt.Println("x is", v)             // here v has type int
case bool, string:
    fmt.Println("x is bool or string") // here v has type interface{}
default:
    fmt.Println("type unknown")        // here v has type interface{}
}
x is bool or string

Further reading

connection-thumb.jpg

Share:             


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK