[SOLVED] Method Pointer Receivers Vs Value Receivers in Golang

In Golang, a method of any datatype has a pointer receiver and method receiver, but before implementing we should note the below points:

  • If we use Value Receivers for implementation then we can use both Method Receivers and Value Receivers while assigning

  • If we use Pointer Receivers for implementation then we can use only Pointer of that can only be used

This error in Golang only occurs when we are unable to understand.

For example, we have an interface of a flag to know this concept better:

type flaginterface{
    Length()
    breath()
}

Then we have a white Flag implementing this flag interface.

type white_flag struct{
    area int
}
package main
import "fmt"
type flag interface {
    length()
    breath()
}
type White_flag struct {
    area int
}
func (White_flag)length(){
    fmt.Println("White_flag length = 10")
}
func(White_flag)breath(){
    fmt.Println("White_flag Breath = 10")
}
func main() {
    var a flag
    a= White_flag{area: 100}
    a.breath()
    a.length()
    a=&White_flag{area: 100}
    a.breath()
    a.length()
}

Go lang output

Here the White_flag structs implement the Rectangle interface with the help of the value receiver. So here it works for both Value Receiver and Pointer Receiver to the variable.

a=&White_flag{area: 100}

a= White_flag{area: 100}

In the following code, we are going to use the pointer

package main
import "fmt"
type flag interface {
    length()
    breath()
}
type White_flag struct {
    area int
}
func (*White_flag)length(){
    fmt.Println("White_flag length = 10")
}
func(*White_flag)breath(){
    fmt.Println("White_flag Breath = 10")
}
func main() {
    var a flag
    a= White_flag{area: 100}
    a.breath()
    a.length()
    a=&White_flag{area: 100}
    a.breath()
    a.length()
}

Go lang Error

While executing this code your code will raise Compilation Error because of this line a= White_flag{area: 100}

Comment this line a= White_flag{area: 100} and execute this you will get Results

Reason

The simple answer is a Pointer Receiver implements only the Pointer of the type can be used but the Value Receiver implements both be and the Pointer of the type.


Further Reading

  1. RuntimeError: Working outside of application context in flask
  2. Why map entries are unddressable in Golang?
  3. [SOLVED] ValueError: View function did not return a response

Monitor your software stack for free with Atatus.

Start your free trial
OR
Request a Demo

Free 14-day trial. No credit card required. Cancel anytime.

Ready to see actionable data?

Avail Atatus features for 14 days free-trial. No credit card required. Instant set-up.