Go: cannot call pointer method getFirstName on "Struct"

Issue

i have simple struct and reciver i try to set the map with the struct and then call reciver
Like that :

package main

import (
    "fmt"
)

type myStruct struct {
    FirstName string 
    LastName string
}

func (m *myStruct) GetFirstName() string {
    return m.FirstName
}

func (m *myStruct) GetLastName() string {
    return m.LastName
}


func main() {
    


    testMyStruct := myStruct {
        FirstName: "x1",
        LastName: "x2",
    }

    myMapStruct["test2"] = testMyStruct 

     

    fmt.Println(myMapStruct["test2"].GetFirstName())



}

Im Getting this error:

 cannot call pointer method getFirstName on myStruct

Why i can call the reciver method from the map ?

Solution

As you are passing a receiver pointer ,you have to use pointer to the struct to call it ,Please look at the below code

package main

import (
    "fmt"
)

type myStruct struct {
    FirstName string 
    LastName string
}

func (m *myStruct) GetFirstName() string {
    return m.FirstName
}

func (m *myStruct) GetLastName() string {
    return m.LastName
}


func main() {
    


    testMyStruct := &myStruct {
        FirstName: "x1",
        LastName: "x2",
    }

  myMapStruct:=make(map[string]*myStruct)

    myMapStruct["test2"] = testMyStruct 

     

    fmt.Println(myMapStruct["test2"].GetFirstName())



}

See working here

or You can use like below if passing receiver as value

package main

import (
    "fmt"
)

type myStruct struct {
    FirstName string 
    LastName string
}

func (m myStruct) GetFirstName() string {
    return m.FirstName
}

func (m myStruct) GetLastName() string {
    return m.LastName
}


func main() {
    


    testMyStruct := myStruct {
        FirstName: "x1",
        LastName: "x2",
    }

  myMapStruct:=make(map[string]myStruct)

    myMapStruct["test2"] = testMyStruct 

     

    fmt.Println(myMapStruct["test2"].GetFirstName())



}

Answered By – Shubh

Answer Checked By – Clifford M. (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.