是否有任何影响(GC流失,性能或其他方面)定义struct函数内部与外部定义?例如:
type Outside struct {
Foo string `json:"foo"`
}
func SomeFunc(b []byte) error {
outside := Outside{}
if err := json.NewDecoder(b).Decode(&outside); err != nil {
return err
}
...
}
Run Code Online (Sandbox Code Playgroud)
与
func SomeFunc(b []byte) error {
type inside struct {
Foo string `json:"foo"`
}
if err := json.NewDecoder(b).Decode(&inside); err != nil {
return err
}
...
}
Run Code Online (Sandbox Code Playgroud)
是否会出现一种优先于另一种情况的情况?
Jos*_*son 10
我的理解是差异只是在可访问性上。
Kon*_*ine 10
对我来说,函数中定义的类型的主要缺点是您无法在该类型上定义方法.
请参阅此示例https://play.golang.org/p/cgH01cRwDv6:
package main
import (
"fmt"
)
func main() {
type MyType struct {
Name string
}
// You cannot define a method on your type
// defined in a function, can you?
func (m MyType) String() string {
return m.Name
}
m := MyType{Name: "Hello, World!"}
fmt.Println(m)
}
Run Code Online (Sandbox Code Playgroud)
以上示例将失败并显示错误prog.go:15:27: expected ';', found 'IDENT' string (and 1 more errors).
性能没有差异,只是范围的差异(即可以看到类型定义的地方)。如果只需要单个函数中的类型,则可以在其中定义它。
正如其他人指出的那样,如果您在包级别(即,在函数外部)定义一种类型,且其名称以大写字母开头,则该类型将被导出(即,在包外部可见)。如果名称不是以大写字母开头,则仅在包装内可见。
| 归档时间: |
|
| 查看次数: |
9689 次 |
| 最近记录: |