我知道函数和方法之间的区别。但我对以下用法感到困惑:
prod:=Product{"title","brand","model"}
prod.Add()
或:
prod:=Product{"title","brand","model"}
products.Add(&prod) // products is package
最佳答案
这是两种截然不同的情况,一种是方法属于Product
实例,一种是全局函数属于产品
包。
type Product struct {
Title string
Brand string
Model string
}
// This method add value to a field in Product
func (p *Product) Add(field, value string) {
switch field {
case "Title":
p.Title = value
case "Brand":
p.Brand = value
case "Model":
p.Model = value
}
}
上面提供了一种方法来为自身增加值(value)作为Product
的一个实例,即
product1 := &Product{}
product1.Add("Title", "first_title")
第二种情况是从product
包中公开的公共(public)函数。在这种情况下,必须提供 Product
的实例(或指针)作为参数。
package products
func Add(p *Product, field, value string) {
// Same switch-case as above
}
Add
函数可以在任何其他包中使用。
package main
import (
"path/to/products"
)
type Product struct {
// ...
}
func main() {
product1 := &Product{}
products.Add(product1, "Title", "first_title")
通常在您的场景中,第一种方法是首选,因为它封装了管理其自身属性的功能。
第二种情况可能被视为“类方法方法”(对于那些来自 OOP,如 Python 或 Java 的方法),其中包类似于类,而公开的函数类似于更通用且可以使用的类方法跨许多实现相同接口(interface)的类型,如下所示:
package products
// where p is a Product interface
func Add(p Product, field, value string) {
// Same switch-case as above
}
type Product interface {
someMethod()
}
来自另一个包:
package main
import (
"path/to/products"
)
type Car struct {
Title string
Brand string
Model string
}
type Ship struct {
// ...
}
type Airplane struct {
// ...
}
// All types implement `Product` and can be used in `products.Add`
func (c *Car) someMethod() {}
func (s *Ship) someMethod() {}
func (a *Airplane) someMethod() {}
func main() {
plane := &Airplane{}
products.Add(plane, "Model", "Boeing-747")
}
关于go - 方法与函数使用 golang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35187450/