0

Can someone explain what the following syntax means in Go, specifially:

x.([]byte)

I am not sure what this means, is this a cast? But for what method since it is just after a dot?

func of(x interface{}) ByteView {
    if bytes, ok := x.([]byte); ok {
        return ByteView{b: bytes}
    }
    return ByteView{s: x.(string)}
}

Reference: https://github.com/golang/groupcache/blob/master/byteview_test.go#L55

Blankman
  • 259,732
  • 324
  • 769
  • 1,199
  • Check this out https://golang.org/doc/effective_go.html#interface_conversions – ivan.sim Apr 22 '16 at 22:49
  • it's a handy way to get at the concrete type which implements the interface. it's type assertion. the interface{} can accept any type, in this case if that type is []byte then it will be assigned to 'bytes' and 'ok' will indicate that it was that type, i.e. ok is a bool. check this out https://golang.org/ref/spec#Type_assertions – Snowman Apr 22 '16 at 22:50

1 Answers1

9

We refer to this as "type assertion."

This is perfectly documented in the Language Spec. In order to have the whole answer here on SO (since it is the whole answer) and not a link-only answer, I will include it the most relevant information from the spec. This is documentation, not my answer...

For an expression x of interface type and a type T, the primary expression

x.(T)

asserts that x is not nil and that the value stored in x is of type T. The notation x.(T) is called a type assertion.

More precisely, if T is not an interface type, x.(T) asserts that the dynamic type of x is identical to the type T. In this case, T must implement the (interface) type of x; otherwise the type assertion is invalid since it is not possible for x to store a value of type T. If T is an interface type, x.(T) asserts that the dynamic type of x implements the interface T.

If the type assertion holds, the value of the expression is the value stored in x and its type is T. If the type assertion is false, a run-time panic occurs. In other words, even though the dynamic type of x is known only at run time, the type of x.(T) is known to be T in a correct program.

var x interface{} = 7  // x has dynamic type int and value 7 
i := x.(int)           // i has type int and value 7

type I interface { m() }
var y I
s := y.(string)        // illegal: string does not implement I (missing method m) 
r := y.(io.Reader)     // r has type io.Reader and y must implement both I and io.Reader 

A type assertion used in an assignment or initialization of the special form

v, ok = x.(T) 
v, ok := x.(T)
var v, ok = x.(T) 

yields an additional untyped boolean value. The value of ok is true if the assertion holds. Otherwise it is false and the value of v is the zero value for type T. No run-time panic occurs in this case.

Effective Go is another great resource, which also includes a section on Interface conversions and type assertions: https://golang.org/doc/effective_go.html#interface_conversions

Snowman
  • 3,170
  • 1
  • 18
  • 28