cannot convert data (type interface {}) to type string: need type assertion

前端 未结 4 735
予麋鹿
予麋鹿 2020-12-07 07:28

I am pretty new to go and I was playing with this notify package.

At first I had code that looked like this:

func doit(w http.ResponseWriter, r *http         


        
4条回答
  •  一个人的身影
    2020-12-07 07:50

    Type Assertion

    This is known as type assertion in golang, and it is a common practice.

    Here is the explanation from a tour of go:

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

    t := i.(T)
    

    This statement asserts that the interface value i holds the concrete type T and assigns the underlying T value to the variable t.

    If i does not hold a T, the statement will trigger a panic.

    To test whether an interface value holds a specific type, a type assertion can return two values: the underlying value and a boolean value that reports whether the assertion succeeded.

    t, ok := i.(T)
    

    If i holds a T, then t will be the underlying value and ok will be true.

    If not, ok will be false and t will be the zero value of type T, and no panic occurs.

    NOTE: value i should be interface type.

    Pitfalls

    Even if i is an interface type, []i is not interface type. As a result, in order to convert []i to its value type, we have to do it individually:

    // var items []i
    for _, item := range items {
        value, ok := item.(T)
        dosomethingWith(value)
    }
    

    Performance

    As for performance, it can be slower than direct access to the actual value as show in this stackoverflow answer.

提交回复
热议问题