Golang: Mutability and pass variable as reference using a pointer


In this note I will show you about mutating a variable value using pointer in Golang Programming:

Sample 1:


package main

import "fmt"

type Artist struct {
    Name, Genre string
    Songs       int
}

func newRelease(a Artist) int {
    a.Songs++
    return a.Songs
}

func main() {
    me := Artist{Name: "Matt", Genre: "Electro", Songs: 42}
    fmt.Printf("%s released their %dth song\n", me.Name, newRelease(me))
    fmt.Printf("%s has a total of %d songs", me.Name, me.Songs)
}

Output:

output1.png

Output text:

Matt released their 43th song

Matt has a total of 42 songs

Sample 2:


package main

import "fmt"

type Artist struct {
    Name, Genre string
    Songs       int
}

func newRelease(a *Artist) int {
    a.Songs++
    return a.Songs
}

func main() {
    me := &Artist{Name: "Matt", Genre: "Electro", Songs: 42}
    fmt.Printf("%s released their %dth song\n", me.Name, newRelease(me))
    fmt.Printf("%s has a total of %d songs", me.Name, me.Songs)
}

Output:

output2.png

Output text:

Matt released their 43th song

Matt has a total of 43 songs

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s