Go language implements the method summary of string slice assignment

  • 2020-06-03 06:43:43
  • OfStack

preface

There is a lot of string manipulation involved in all programming languages, so you can see how important it is to be familiar with string manipulation. This article details the Go language method of string slice assignment through examples.

1. In range of for cycle


func StrRangeTest() {
  str := []string{"str1", "str2", "str3"}
  for i, v := range str {
   fmt.Println(i, v)
   v = "test"
  }
  fmt.Println(str)}

Results: Assigning v does not change the value of character slice.


0 str1
1 str2
2 str3
[str1 str2 str3]

Conclusion: range is an assigned copy

2. Pass parameters in a function


func Handler() {
  strArr := []string{"str1", "str2", "str3"}
   fmt.Println("before call func:", strArr)
  strFuncTest(strArr)
  fmt.Println("after call func:", strArr)
}

func strFuncTest(strArr []string) {
  strArr[0] = "test"
}

Result: An assignment to a string slice in the function changes the value of the original slice.


[str1 str2 str3]
[test str2 str3]

Conclusion: Function parameter passing is pointer passing

conclusion

The above is the whole content of this article, I hope the content of this article can bring 1 definite help to your study or work, if you have any questions, you can leave a message to communicate.


Related articles: