In Go, passing arguments to functions is done by value, meaning that any changes made to the argument within the function are not reflected in the original variable. This can become problematic when working with mutable data types such as slices, as appending to the slice within the function will not affect the original slice beyond the scope of the function.
Consider the following example:
nums := []int{1, 2, 3} func addToNumbs(nums []int) []int { nums = append(nums, 4) fmt.Println(nums) // []int{1, 2, 3, 4} } fmt.Println(nums) // []int{1, 2, 3}
In this example, the AddToNumbs function takes a copy of the nums slice and appends the value 4. This modifies only the copy within the function, and the original nums slice remains unchanged outside the function.
To resolve this issue, you need to pass the slice by reference. One way to do this is by passing a pointer to the slice:
func myAppend(list *[]string, value string) { *list = append(*list, value) }
By passing a pointer to the slice, any changes made within the function are directly reflected in the original slice. However, passing a pointer also means that the function can modify the slice in ways you may not expect, so it is important to use pointers carefully.
Another alternative is to return the modified slice from the function, as demonstrated in the following example:
func validate(obj Validatable, messages []ValidationMessage) []ValidationMessage { // Append to the accumulator and return it directly messages = append(messages, message) return messages }
In this case, the validate function returns the modified messages slice, eliminating the need for passing a pointer to the slice.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3