代码之家  ›  专栏  ›  技术社区  ›  Arockia

如何将字符串作为参数传递给Golang指针接收函数?[复制]

go
  •  -3
  • Arockia  · 技术社区  · 7 年前

    我正在尝试一个简单的Go结构与值和指针接收器函数。我无法将一个字符串作为参数传递给指针接收器函数以修改结构数据。有人能帮忙吗?

    代码:

    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)
    }
    

    2 回复  |  直到 7 年前
        1
  •  3
  •   cannot_mutably_borrow    7 年前
    func (b *book) changeAuthor(author string) {
       b.author = author
    }
    

    changeAuthor 没有返回类型。你不能使用 Println 或在您的情况下需要参数的任何其他函数/方法。

    要解决这个问题,首先可以将作者改为 book.changeAuthor("arulnathan") 还有指纹呢 book.author

        2
  •  0
  •   KibGzr    7 年前

    你不能打印 changeAuthor 但它什么也不回。

    book.changeAuthor("arulnathan")
    fmt.Println(book.author)