go - 方法与函数使用 golang

标签 go

我知道函数和方法之间的区别。但我对以下用法感到困惑:

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/

相关文章:

google-app-engine - Permission Denied error 从 appengine go 调用外部服务

firebase - 无法访问 Firebase 函数中自动填充的环境变量

GoLang 和 MySQL 数据库

string - 奇怪的行为,同时变量与函数的输入和输出相同

xml - Golang 解码 MusicXML

concurrency - Func 不会运行;增量 channel

string - 从 Go 中的 slice 中删除字符串

go - 从 golang net/http 库记录和解码响应体

dictionary - 动态添加键值映射到结构

html - 在 golang html 模板中访问 {{range .}} 范围之外的结构变量