Static class method in go language

huangapple go评论89阅读模式
英文:

Static class method in go language

问题

我正在查看这个网址上的示例代码:https://golang.org/pkg/net/rpc/

type Arith int

func (t *Arith) Multiply(args *Args, reply *int) error {
    *reply = args.A * args.B
    return nil
}

从面向对象的角度来看,Multiply 看起来像是一个静态方法,它不访问 Arith 类中的任何数据;因为变量 t 没有被使用。这是否意味着 type Arith int 中的 int 没有任何意义?

英文:

I am looking at the example code at: https://golang.org/pkg/net/rpc/

type Arith int

func (t *Arith) Multiply(args *Args, reply *int) error {
    *reply = args.A * args.B
    return nil
}

From an OOP perspective, Multiply seems like a static method which doesn't access any data in Arith class; as the variable t is not used. Does it mean that int in type Arith int does not have any significance?

答案1

得分: 4

这与面向对象编程(OOP)无关,只是rpc包的约定是通过从一个“对象”(这里的对象指的是具有非空方法集的任何值)导出方法。

intArith的类型中是有意义的,但在这个特定的例子中并不重要,因为接收器在方法中从未被引用。

所以是的,这个例子有点像静态类,但是请不要将Java的OOP思想映射到Go中,因为Go非常不同,没有“类”或继承。

英文:

This doesn't have anything to do with OOP, it's simply that the rpc package's convention works by exporting methods from an "object" (with object here meaning any value with a non-empty method set)

The int is significant as the type of Arith, but it's not significant in this particular example, since the receiver is never referenced in the methods.

So yes, this example is kind of like a static class, but try not to map Java OOP ideas to Go, because Go is very different, as there are no "classes" or inheritance.

答案2

得分: 1

另一种称呼模拟静态方法的方式,尽管它实际上并不是静态方法,如下所示:

package main

import "fmt"

type Arith struct {
}

func (Arith) Multiply(a float32, b float32) float32 {
    return a * b
}

func main() {
    result := (Arith).Multiply(Arith{}, 15, 25)
    fmt.Println(result)
}

但从我的观点来看,将这个方法放在一个名为arith的单独包中,而不是类Arith之外,会更容易理解。

英文:

Another way to call simulating an static method, despite the fact it isn't, is as follows:

package main
 
import "fmt"
 
type Arith struct {
}

func (Arith) Multiply(a float32, b float32) float32 {
	return a * b
}
 
func main() {
    result := (Arith).Multiply(Arith{}, 15, 25)
	fmt.Println(result)
}

But from my point of view, it is less understandable than placing this method in a separate package arith outside from class Arith

huangapple
  • 本文由 发表于 2016年1月4日 02:50:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/34580253.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定