What kind of type conversion is supported by Go?
What kind of type conversion is supported by Go?
Go supports various kinds of type conversions, primarily between compatible types, and it also provides mechanisms for converting between interfaces and concrete types. Here's a detailed look at the type conversion support in Go:
Go allows conversion between different numeric types, provided they are compatible with one another. This means that the underlying data structure of the types should be the same or convertible. For instance, you can convert between different integer types (int
, int64
, etc.) and between floating-point types (float32
, float64
). However, you cannot directly convert between incompatible types like int
and string
without using a function that performs the conversion[2][5].
The syntax for converting from one type to another is straightforward:
variableOfTypeT2 := T2(variableOfTypeT1)
For example, converting an int
to a float64
:
var i int = 42
var f float64 = float64(i)
And converting a []byte
to a string
:
greeting := []byte("hello world")
greetingStr := string(greeting)
Interfaces in Go are types that define a set of methods but do not implement them. A type implements an interface by implementing its methods. You can convert between interfaces as long as the underlying concrete type implements the methods of the target interface[2].
Go allows for the conversion between numeric types with special rules. For example, an int
can be converted to a float64
, and a float64
can be converted back to an int
, though the fractional part will be discarded in the latter case. Strings can be converted to byte arrays and vice versa[2].
Type assertions are a way to retrieve the dynamic value of an interface. While not a type conversion in the traditional sense, type assertions allow you to extract the concrete value stored in an interface varia...
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào