在函数内部定义struct与在外部定义ojit_code有什么关系(GC搅动,性能或其他)?例如:

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
  }

  ...
}


func SomeFunc(b []byte) error {

  type inside struct {
    Foo string `json:"foo"`
  }

  if err := json.NewDecoder(b).Decode(&inside); err != nil {
    return err
  }

  ...
}

在任何情况下都会有人偏爱一个吗?

最佳答案

对我来说,在函数中定义的类型的主要缺点是您不能在该类型上定义方法。

参见以下示例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)
}

上面的示例将失败,错误为prog.go:15:27: expected ';', found 'IDENT' string (and 1 more errors)

关于go - 在函数内部还是外部定义结构的含义?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42010112/

10-12 00:21
查看更多