Golang中,可以使用返回接口的方式进行映射。

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

Golang, Go : mapping with returning interface?

问题

这段代码是Go语言的示例代码,它定义了一个函数OrderedBy,该函数返回一个multiSorter类型的指针。multiSorter是一个排序器,它使用传入的less函数按顺序进行排序。调用Sort方法可以对数据进行排序。

这段代码中的冒号并不是映射或闭包,它是用来声明函数的返回类型。在Go语言中,函数的返回类型放在函数名后面,使用冒号进行分隔。

如果你想要理解Go语言中的这种语法,可以阅读Go语言的官方文档,特别是关于函数和方法的部分。你可以从官方网站上的这个链接开始:http://golang.org/doc/

英文:

http://golang.org/pkg/sort/

This is from Go example.

 // OrderedBy returns a Sorter that sorts using the less functions, in order.
// Call its Sort method to sort the data.
func OrderedBy(less ...lessFunc) *multiSorter {
 	return &multiSorter{
    	changes: changes,
     	less:    less,
    }
}

What does this do by colon? Is it mapping? Is it closure? Too much new syntax here. What should I read to understand this syntax in Go?

答案1

得分: 1

这是一个工厂函数,用于创建和初始化一个名为multisorter的结构体:

https://sites.google.com/site/gopatterns/object-oriented/constructors

此外,Go语言中可以使用工厂函数内的初始化器来简洁地编写"构造函数":

func NewMatrix(rows, cols, int) *matrix {
    return &matrix{rows, cols, make([]float, rows*cols)}
}

在初始化时,它还使用了命名参数:

http://www.golang-book.com/9

这段代码为所有字段分配内存,并将它们都设置为零值,然后返回一个指针。(Circle)通常情况下,我们希望为每个字段赋予一个值。我们可以通过两种方式实现。像这样:

c := Circle{x: 0, y: 0, r: 5}
英文:

It's a factory function, creating and initialising a struct of type multisorter:

https://sites.google.com/site/gopatterns/object-oriented/constructors

Additionally, Go "constructors" can be written succinctly using initializers within a factory function:

function NewMatrix(rows, cols, int) *matrix {
    return &matrix{rows, cols, make([]float, rows*cols)}
}

Also, it is using named parameters when initialising:

http://www.golang-book.com/9

This allocates memory for all the fields, sets each of them to their zero value and returns a pointer. (Circle) More often we want to give each of the fields a value. We can do this in two ways. Like this:

c := Circle{x: 0, y: 0, r: 5}

答案2

得分: 1

在函数声明中,less ...lessFunc 的意思是:可以传递任意数量的参数,每个参数的类型都是 lessFunc,并且这些参数将会被存储在切片 less 中。

因此,它创建了一个 multiSorter 结构体,该结构体支持排序接口。调用该接口的排序方法(由 multiSorter 实现)将会在排序过程中依次使用每个 lessFunc

这样说清楚了吗?如果需要的话,我可以进一步展开解释。

英文:

<p>The less ...lessFunc in the func declaration means:</p>
any number of parameters, each of type lessFunc can be passed here, and will be stored in the slice less
<p>So it creates a multiSorter struct, which supports the sort interface, and calling the sort method from that interface (and implemented by multiSorter) will cause the object to use each lessFunc in turn while sorting</p>
<p>Does this make sense? I can expand more if needed...</p>

huangapple
  • 本文由 发表于 2013年10月12日 13:52:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/19331050.html
匿名

发表评论

匿名网友

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

确定