This question already has an answer here:
I am trying one simple Go struct with value and pointer receiver functions. I am not able to pass one string as an argument to pointer receiver function to modify the struct data. Can anyone please help on this?
Code:
package main
import (
"fmt"
)
type book struct {
author string
name string
category string
price int16
}
func (b book) greet() string {
return "Welcome " + b.author
}
func (b *book) changeAuthor(author string) {
b.author = author
}
func main() {
book := book{author: "Arockia",
name: "Python shortcuts",
category: "IT",
price: 1500}
fmt.Println(book.author)
fmt.Println(book.greet())
fmt.Println(book.changeAuthor("arulnathan"))
fmt.Println(book.author)
}
Error:
.\struct_sample.go:29:31: book.changeAuthor(string("arulnathan")) used as value
</div>
You can not print changeAuthor
while it return nothing.
book.changeAuthor("arulnathan")
fmt.Println(book.author)
func (b *book) changeAuthor(author string) {
b.author = author
}
changeAuthor
does not have a return type. You cannot use Println
or any other function/method which expects a parameter in your case.
To solve this, first you can change your author as book.changeAuthor("arulnathan")
and the print book.author
.