I have a type alias for a slice. And I want to be able to append to the slice (or filter from the slice) when the slice is a pointer receiver:
package main import ( "fmt" ) type itself []string func (h itself) appendToItself(test string) { h = append(h, test) } func main() { h := itself{"1", "2"} h.appendToItself("3") fmt.Println(h, "<- how do I make it [1,2,3]") }
Log:
[1 2] <- how do I make it [1,2,3]
The append built-in function appends elements to the end of a slice. If it has sufficient capacity, the destination is resliced to accommodate the new elements. If it does not, a new underlying array will be allocated. Append returns the updated slice.
the memory block containing the slice elements is passed by "reference". The slice information triplet holding the capacity, the number of element and the pointer to the elements is passed by value.
Slices are pointers to arrays, with the length of the segment, and its capacity. They behave as pointers, and assigning their value to another slice, will assign the memory address.
map, pointer and slice types are reference types in Go. map, pointer, slice, channel, function and interface types are reference types.
The built-in append function appends any number of elements to the end of a slice. Append returns the updated slice and it does not modify the existing one. So it is Pure function in terms of Javascript. The resulting value of append () function is a slice containing all the elements of the original slice plus the provided values.
It is a common belief that slices are passed by reference, in fact, the following example will print [b,b] and [b,b] even if the slice was initialized to [a,a] since it got modified during the execution of the literal function and the change is visible to the main. Making use of pointers leads to the same result, in fact, the following code
The answer to the questions, then, is simple, but hidden inside the implementation of the slice itself: The pointer to a slice is indispensable when the function is going to modify the structure, the size, or the location in memory of the slice and every change should to be visible to those who call the function.
This function appends the new element at the end of the slice. Here, this function takes s slice and x…T means this function takes a variable number of arguments for the x parameter. Such type of function is also known as a variadic function.
You need to actually pass a pointer, try:
package main import ( "fmt" ) type itself []string func (h *itself) appendToItself(test string) { *h = append(*h, test) } func main() { h := itself{"1", "2"} h.appendToItself("3") fmt.Println(h, "<- how do I make it [1,2,3]") }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With