Golang嵌套函数内部的类 [英] Golang nested class inside function
问题描述
< code $ func f(){
//嵌套结构Cls在f
类型中Cls struct {
...
}
//尝试边界foo到Cls但没有
func(c * Cls)foo(){
...
}
}
因此,感觉有点奇怪,因为类在函数内部变弱了。
任何提示?
实际上,如果您想用或声明功能而不用一个接收器:在Go中嵌套函数是不允许的。
虽然你可以使用 创建了一个变量 请试试去游乐场。 Go supports nested struct inside function but no nested function except lambda, does it mean there is no way to define a nested class inside function? Thus it feels a bit strange that class is weaken inside function. Any hints? Actually it doesn't matter if you want to declare the function with or without a receiver: nesting functions in Go are not allowed. Although you can use Function literals to achieve something like this: Here we created a variable Try it on Go Playground. 这篇关于Golang嵌套函数内部的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
func f(){
foo:= func(s string){
fmt.Println(s)
}
foo(Hello World!)
}
foo
,它有一个函数类型,并且在另一个函数 f
内部被扩展。按照预期,调用外部函数 f
输出:Hello World!
func f() {
// nested struct Cls inside f
type Cls struct {
...
}
// try bounding foo to Cls but fail
func (c *Cls) foo() {
...
}
}
func f() {
foo := func(s string) {
fmt.Println(s)
}
foo("Hello World!")
}
foo
which has a function type and it is delcared inside another function f
. Calling the "outer" function f
outputs: "Hello World!"
as expected.