在这段代码中,T代表什么?

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

What is T in this code

问题

这段代码中的T到底是什么意思?递归声明吗?

package main

import "fmt"

type T func() T

func main() {
    var a T
    a = func() T {
        return a
    }

    fmt.Printf("%#v", a)
}

这段代码定义了一个类型T,它是一个函数类型,该函数没有参数,并返回类型为T的值。在main函数中,声明了一个变量a,类型为T。然后,将一个匿名函数赋值给a,该匿名函数返回a本身。最后,使用fmt.Printf函数打印出变量a的值。

这段代码的作用是创建一个递归的函数类型。当调用a时,它会返回自身,实现了递归的效果。

英文:

What really T is in this piece of code? recursive deceleration?

package main

import "fmt"

type T func() T

func main() {
	var a T
	a = func() T {
		return a
	}

	fmt.Printf("%#v", a)
}

http://play.golang.org/p/zt4CBXgrmI

Edit: I have been using Go for more than a year.

答案1

得分: 9

看起来这是一个函数类型。在声明中,T是一个无参数函数,返回类型为T,也就是返回一个函数的函数。这就是类型声明。a是这个类型T的实例。

a是一个返回自身的函数,所以这些代码行基本上都是相同的:

fmt.Printf("%#v", a)
fmt.Printf("%#v", a())
fmt.Printf("%#v", a()()()()())

我想不出这个用法的好处,但是我对Go语言并不是很熟悉。

英文:

It looks like a function type. In the declaration, T is a parameterless function that returns a T, so a function that returns a function. That is the type declaration. a is of this type T.

a is a function that returns itself, so these lines basically all do the same:

fmt.Printf("%#v", a)
fmt.Printf("%#v", a())
fmt.Printf("%#v", a()()()()())

I can't think of a good use for this, but then again, I'm far from experienced in Go.

答案2

得分: 0

GolezTrol是正确的。T是类型,tT类型的变量。
t包含对函数的引用。

我添加了返回int而不是S的函数类型S,并比较了它的工作方式和返回值。

http://play.golang.org/p/2VRqmMVQR9

英文:

GolezTrol is correct. T is type. t is variable of T type.
t contain reference to function

I added type S of function that returns int instead of S and compared how it work and what it returns

http://play.golang.org/p/2VRqmMVQR9

huangapple
  • 本文由 发表于 2013年11月27日 06:15:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/20229116.html
匿名

发表评论

匿名网友

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

确定