Câu hỏi phỏng vấn Golang
Câu hỏi

What kind of type conversion is supported by Go?

Câu trả lời

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:

Basic Type Conversions

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:

go Copy
variableOfTypeT2 := T2(variableOfTypeT1)

For example, converting an int to a float64:

go Copy
var i int = 42
var f float64 = float64(i)

And converting a []byte to a string:

go Copy
greeting := []byte("hello world")
greetingStr := string(greeting)

Type Conversion Between Interfaces

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].

Numeric Conversions

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

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

junior

Gợi ý câu hỏi phỏng vấn

senior

What is an idiomatic way of representing enums in Go?

junior

How to efficiently concatenate strings in Go?

junior

What are some advantages of using Go?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào