Hands-On System Programming with Go
上QQ阅读APP看书,第一时间看更新

Casting

Converting a type into another type is an operation called casting, which works slightly differently for interfaces and concrete types:

  • Interfaces can be casted to a concrete type that implements it. This conversion can return a second value (a Boolean) and show whether the conversion was successful or not. If the Boolean variable is omitted, the application will panic on a failed casting.
  • With concrete types, casting can happen between types that have the same memory structure, or it can happen between numerical types:
type N [2]int                // User defined type
var n = N{1,2}
var m [2]int = [2]int(N) // since N is a [2]int this casting is possible

var a = 3.14 // this is a float64
var b int = int(a) // numerical types can be casted, in this case a will be rounded to 3

var i interface{} = "hello" // a new empty interface that contains a string
x, ok := i.(int) // ok will be false
y := i.(int) // this will panic
z, ok := i.(string) // ok will be true

There's a special type of conditional operator for casting called type switch which allows an application to attempt multiple casts at once. The following is an example of using interface{} to check out the underlying value:

func main() {
var a interface{} = 10
switch a.(type) {
case int:
fmt.Println("a is an int")
case string:
fmt.Println("a is a string")
}
}