Golang: Append via Function Receiver

type User struct {
	id   int
	name string
}

Create new type that holds slice of user struct.

type Users []User

Create function receiver for our new type.

func (us *Users) add(u User) {

	fmt.Printf("%T", us)

	// Output: *main.Users

	fmt.Printf("%T", *us)
	// Output: main.Users

	*us = append(*us, u)
}

In our main function we can use it to add user struct to the slice.

myUsers := Users{}

fmt.Println(myUsers)
// Output: []

myUsers.add(User{
	id:   1,
	name: "user1",
})

fmt.Println(myUsers)
// Output: [{1 user1}]

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *