Go的功能是什么,看起来像演员一样[重复]

Go的功能是什么,看起来像演员一样[重复]

问题描述:

This question already has an answer here:

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

</div>

此问题已经存在 在这里有答案: p>

  • Go代码中的“ err。(* exec.ExitError)”是什么? 2个答案 span> li> ul> div>

    有人可以 详细说明以下语法在Go中的含义: p>

      x。([[byte])
      code>  pre> 
     
     

    我不确定这是什么意思,这是演员吗? 但是对于什么方法,因为它只是在一个点之后? strong> p>

     (x接口{})ByteView {
    ,如果有字节,可以:= x。  ([]字节);  ok {
    返回ByteView {b:字节} 
    } 
    返回ByteView {s:x。(string)} 
    } 
      code>  pre> 
     
     

    参考文献: https://github.com/golang/groupcache/blob/master/byteview_test。 go#L55 p> div>

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