-2

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?

Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130
Honddoe
  • 51
  • 11

1 Answers1

5

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)
}
novalagung
  • 10,905
  • 4
  • 58
  • 82