Golang nested class inside function

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

Golang nested class inside function

问题

在Go语言中,函数内部支持嵌套结构体(nested struct),但除了lambda函数之外,不支持嵌套函数。这是否意味着无法在函数内部定义嵌套类(nested class)呢?

在Go语言中,没有直接支持嵌套类的语法。嵌套类通常用于在类内部定义辅助类或私有类。然而,你可以通过将类定义在包级别(package level)来模拟嵌套类的效果。这样做可以使得类的定义在函数内部可见,但仍然具有包级别的作用域。

以下是一个示例:

package main

import "fmt"

type Outer struct {
    // Outer类的成员
    Inner struct {
        // Inner类的成员
        value int
    }
}

func main() {
    o := Outer{}
    o.Inner.value = 42
    fmt.Println(o.Inner.value) // 输出: 42
}

在上面的示例中,我们在Outer类内部定义了一个Inner类。尽管Inner类在Outer类内部定义,但它的作用域是包级别的,因此在main函数中可以访问到它。

希望这可以帮助到你!

英文:

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?

func f() {
    // nested struct Cls inside f
    type Cls struct {
    ...
    }
    // try bounding foo to Cls but fail
    func (c *Cls) foo() {
    ...
    }
}

Thus it feels a bit strange that class is weaken inside function.

Any hints?

答案1

得分: 22

实际上,无论你是要在函数声明中使用接收器还是不使用接收器,都没有关系:在Go语言中,不允许嵌套函数。

尽管如此,你可以使用函数字面量来实现类似的功能:

func f() {
    foo := func(s string) {
        fmt.Println(s)
    }

    foo("Hello World!")
}

在这里,我们创建了一个名为foo的变量,它具有函数类型,并且它是在另一个函数f内部声明的。调用"外部"函数f会输出预期的结果:"Hello World!"。

你可以在Go Playground上尝试一下。

英文:

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:

func f() {
	foo := func(s string) {
		fmt.Println(s)
	}

	foo("Hello World!")
}

Here we created a variable foo which has a function type and it is declared inside another function f. Calling the "outer" function f outputs: "Hello World!" as expected.

Try it on Go Playground.

答案2

得分: 0

我为icza的答案点了赞,但只是为了稍微扩展一下,这里是他的示例稍作修改,展示了外部函数中定义的变量对内部函数是可见的:

func f(s string) {
    foo := func() {
        fmt.Println(s)
    }

    foo()
}

func main() {
    f("Hello, World!\n")
}
英文:

I upvoted icza's answer but just to extend it a little, here's his example slightly modified, showing that variables defined in the outer function are visible to the inner function:

    func f(s string) {
        foo := func() {
            fmt.Println(s)
        }

        foo()
    }

    func main() {
        f("Hello, World!\n")
    }

huangapple
  • 本文由 发表于 2015年1月31日 21:28:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/28252117.html
匿名

发表评论

匿名网友

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

确定