SoFunction
Updated on 2025-03-05

Summary of the method of implementing string slice assignment in Go language

Preface

There are a large number of string operations involved in all programming languages, which shows how important it is to be familiar with the operation of strings. This article introduces the method of implementing string slice assignment in Go through examples. Interested friends, please follow the editor to take a look.

1. In the range of the for loop

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

result:Assigning value to v will not change the value of the character creation slice.

0 str1
1 str2
2 str3
[str1 str2 str3]

in conclusion:range is an assignment copy

2. Passing parameters in the function

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

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

result:Assigning a string slice in the function will change the value of the original slice.

[str1 str2 str3]
[test str2 str3]

in conclusion:The function parameter is passed by a pointer

Summarize

The above is the entire content of this article. I hope the content of this article will be of some help to your study or work. If you have any questions, you can leave a message to communicate.