Hello everyone, I am fried fish.
Some time ago, Maimai was engaged in a discussion series of "Let me come up with an interview question". One of the friends of Maimai @ Xiaodonggua, who visited Cebu, asked a Go topic.
Come and join Jianyu to answer whether your answer is accurate or not, and how is your knowledge?
(Everyone said it was very simple, the result was 50 50 in the vote, and more people were wrong...)
topic
The Go topics are as follows:
func main() {
var nums1 []interface{}
nums2 := []int{1, 3, 4}
num3 := append(nums1, nums2)
fmt.Println(len(num3))
}
Please select what is the result (answer) of the program?
- A: 1;
- B: 3;
- C: 4;
- D: Compilation failed.
Answer
The subject seems to be a friend of Xichang College. Here is the picture of the original question (block the answer, and then look down after selecting the multiple-choice question).
As shown below:
Program running result:
1
That is, the answer is A, and the output is 1.
Did you get it right? We continue.
Since the length of the variable num3 is 1. So what is stuffed in one mile here?
code show as below:
var nums1 []interface{}
nums2 := []int{1, 3, 4}
num3 := append(nums1, nums2)
fmt.Println(num3)
Is the output 1, or 3, or 4?
Program running result:
[[1 3 4]]
Did you get it right this time?
Why?
Parse
In essence, this Go topic is relatively easy to be misled, and one accidentally chooses the wrong one. Let's see what the official definition of the append function looks like.
The following function signature:
func append(slice []Type, elems ...Type) []Type
The official description of the function is: the append function appends elements to the end of the slice.
Take a closer look at the code snippet in the title:
var nums1 []interface{}
nums2 := []int{1, 3, 4}
num3 := append(nums1, nums2)
Combining the definition, we can know that the element nums2 will be appended to the end of the nums1 variable, and there will be no situation where the values in the variable are disassembled and added separately.
Naturally, the length of the variable num3 will only be equal to 1, and this 1 is the element in the nums2 variable. Very natural and unprocessed.
Summarize
This question is not logically complicated. But when some things in Go are used, it is easy to make mistakes due to subconscious understanding.
Have you encountered these questions in interviews or at work? Welcome to leave a message and exchange in the comment area.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。