Change value receiver to pointer receiver

I am reading the blog at Slices. At one point there is a piece of code like

type path []byte

func (p path) ToUpper() {
    for i, b := range p {
        if 'a' <= b && b <= 'z' {
            p[i] = b + 'A' - 'a'
        }
    }
}

func main() {
    pathName := path("/usr/bin/tso")
    pathName.ToUpper()
    fmt.Printf("%s\n", pathName)
}

The tutorial asks that the above code should be changed so that it takes a pointer receiver. I am new to go and dont understand pointers much. Can someone point me towards how the above example can be done with pointer receivers. Thanks

Receivers are just a special syntax for the first argument of a function. For example, you could also write func ToUpper(p path). Changing from a value receiver to a pointer receiver is the same as changing an argument from a value to a pointer. In this case, func (p *path) ToUpper() {... (note the asterisk). You’ll also have to dereference p in your code.

If this is still confusing, then perhaps you may be confused about the distinction between pointers and values?

1 Like

Thanks Craig. Yes, I am confused with the pointer. I understand abit of pointer but not that much that I could modify the program to have a pointer receiver.

There is a great course on Udemy by Todd McLeod and he has a great explanation on pointers. Here is the link. The course is not free but there is a coupon code “formyfriend” (hope it still works for you) that he gives out in another YouTube video that allows you to take it for free. Cool guy! Check it out and I am sure after watching the section on pointers it will make a lot for sense to you.

The point of the example in the tutorial “Slices” is to demonstrate that passing a copy of the slice value as the method receiver is the same as passing a pointer to the slice value - they have the same backing array so the ToUpper() method works in both cases.

If you are interested in the difference between value and pointer receivers then something like https://play.golang.org/p/XBj4MKNL6C and https://play.golang.org/p/DQfgRWrCn0 would be more interesting. The pointer case also demonstrates that you can invoke a method with a pointer receiver without explicitly calling it with a pointer value (&pathName.ToUpper()) - the compiler handles that for you.

https://play.golang.org/p/feqeAlb80z

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.