doutao4938 2018-11-19 04:07
浏览 30
已采纳

Golang语言中的项目(推文),这是什么意思?

I found the following code in Golang language

item.(Tweet)

I already know that there is a method for each variable. But I don't know the code above. Does anyone know?

  • 写回答

1条回答 默认 最新

  • dtqf81594 2018-11-19 04:11
    关注

    It's called type assertions.

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

    Example:

    var num interface{} = 5
    var numActual int = num.(int)
    
    fmt.Println(numActual)
    

    On code above, num is a variable whom type is interface{}. It can hold any kind of value, but in example above it's storing a numeric int data, 5.

    To get the underlying concrete value from num, simply add .(type) on the end of the variable.

    num.(int)
    

    You can check whether an interface{} variable is convertible into certain type or not, by checking the 2nd return value of the statement. Example:

    if actual, ok := num.(string); !ok {
        fmt.Println("num is not string")
        fmt.Println("it's a number data with value is", actual)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?