-4

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

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Arockia
  • 440
  • 1
  • 6
  • 18

2 Answers2

3
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.

0

You can not print changeAuthor while it return nothing.

book.changeAuthor("arulnathan")
fmt.Println(book.author)
KibGzr
  • 2,053
  • 14
  • 15