我知道 func 和 method 之间的区别。但我对以下之间的用法感到困惑:
prod:=Product{"title","brand","model"}
prod.Add()
Run Code Online (Sandbox Code Playgroud)
或者:
prod:=Product{"title","brand","model"}
products.Add(&prod) // products is package
Run Code Online (Sandbox Code Playgroud)
这是两种不同的情况,一种是方法属于Product实例,一种是全局函数属于products包。
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
}
}
Run Code Online (Sandbox Code Playgroud)
上面提供了一个方法来给自己添加值作为 的实例Product,即
product1 := &Product{}
product1.Add("Title", "first_title")
Run Code Online (Sandbox Code Playgroud)
第二种情况是从product包中公开的公共函数。在这种情况下,Product必须提供a 的实例(或指针)作为参数。
package products
func Add(p *Product, field, value string) {
// Same switch-case as above
}
Run Code Online (Sandbox Code Playgroud)
Add 函数然后可以从任何其他包中使用。
package main
import (
"path/to/products"
)
type Product struct {
// ...
}
func main() {
product1 := &Product{}
products.Add(product1, "Title", "first_title")
Run Code Online (Sandbox Code Playgroud)
通常在您的场景中,首选第一种方法,因为它封装了管理其自身属性的功能。
第二种情况可能被视为“类方法方法”(对于那些来自 Python 或 Java 等 OOP 的方法),其中包类似于类,而公开的函数类似于类方法,这些方法更通用,可用于多种类型实现相同的接口,如下所示:
package products
// where p is a Product interface
func Add(p Product, field, value string) {
// Same switch-case as above
}
type Product interface {
someMethod()
}
Run Code Online (Sandbox Code Playgroud)
从另一个包中:
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")
}
Run Code Online (Sandbox Code Playgroud)