Is the colleague who was in the append element in the for loop yesterday still there?

The problem

package main

import "fmt"

func main(a) {
 s := []int{1.2.3.4.5}  for _, v:=range s {  s =append(s, v)  fmt.Printf("len(s)=%v\n".len(s))  } } Copy the code

Does this code cause an infinite loop?

How to answer

  • It doesn’t cycle forever.for rangeIs actuallygolangtheSyntactic sugarGets the length of the slice before the loop beginsLen (slice), and then executeLen (slice)Number of cycles.

explain

  • for rangeThe source is
// The loop we generate:
// for_temp := range
// len_temp := len(for_temp)
// for index_temp = 0; index_temp < len_temp; index_temp++ {
// value_temp = for_temp[index_temp]
// index = index_temp // value = value_temp // original body // } Copy the code
  • The above code will be considered by the compiler
func main(a) {
 s := []int{1.2.3.4.5}
 for_temp := s
 len_temp := len(for_temp)
 for index_temp := 0; index_temp < len_temp; index_temp++ {
 value_temp := for_temp[index_temp]  _ = index_temp  value := value_temp  // The following is the original body  s =append(s, value)  fmt.Printf("len(s)=%v\n".len(s))  } } Copy the code
  • Code run output
len(s)=6
len(s)=7
len(s)=8
len(s)=9
len(s)=10
Copy the code

So, the colleague was using golang?

Article recommendation:

  • Interviewer Golang: For select, what happens if the channel is already closed? What if there’s only one case?
  • Golang interview question: What happens if I can read and write a chan that is already closed? Why is that?
  • Golang interview question: What happens if I read and write to an uninitialized chan? Why is that?
  • Golang Interview Question: How does Reflect get the field tag? Why can’t json packages export tags for private variables?
  • Golang: What happens if you don’t tag a VARIABLE in a JSON package?
  • Golang interview question: How to avoid memory escape?
  • Golang: What about memory escapes?
  • Golang Interview question: Does memory copy occur when a string is converted into a byte array?
  • Golang interview question: Flip containsChinese, numbers and English lettersThe string
  • Golang interview question: Is copying large slices more expensive than small slices?
  • Golang interview question: Can you tell the difference between uintptr and unsafe.pointer?
If you want to learn one thing every day?