In Golang, assertion is the process of verifying that a value belongs to a specific type. It is used to check if an interface value holds a specific type or not. The syntax for an assertion is:
value, ok := interface_value.(type_name)
Here, value is the value of the interface type, ok is a boolean value that indicates whether the assertion was successful or not, and type_name is the type that you want to assert. If the assertion is successful, the value of the interface is returned as value, and ok is set to true. Otherwise, value is set to the zero value of the type, and ok is set to false.
For example, consider the following code:
var i interface{} = “hello”
s, ok := i.(string)
In this example, we have declared an interface variable i and initialized it with a string value “hello”. We then assert that i is a string type and assign the result to the variables s and ok. Since i is a string, s will be assigned the value “hello” and ok will be true.
If the assertion fails, then ok will be false and value will be set to the zero value of the type. For example, consider the following code:
var i interface{} = 10
s, ok := i.(string)
In this case, the assertion fails because i is not a string type. Therefore, s will be assigned an empty string, which is the zero value of the string type, and ok will be false.
Practice Questions on assertion in Golang
Here are some practice questions on assertion in Golang:
What is the output of the following Go code?
var i interface{} = 10
s, ok := i.(string)
fmt.Println(s, ok)
A. 10 true
B. “” false
C. 0 false
D. panic
Answer: B
Which keyword is used to perform an assertion in Golang?
A. assert
B. check
C. verify
D. type
Answer: D
What is the syntax for asserting that an interface value holds a slice of integers?
A. value, ok := interface_value.(int)
B. value, ok := interface_value.([]int)
C. value, ok := interface_value.(string)
D. value, ok := interface_value.(float64)
Answer: B
What is the output of the following Go code?
var i interface{} = []int{1, 2, 3}
s, ok := i.(string)
fmt.Println(s, ok)
A. [1 2 3] true
B. [] false
C. 0 false
D. panic
Answer: B
What is the output of the following Go code?
var i interface{} = “hello”
s := i.(string)
fmt.Println(s)
A. hello
B. “”
C. panic
D. nil
Answer: A