Implications of defining a struct inside a function vs outside?

Are there any implications (GC churn, performance, or otherwise) to defining an struct inside a function vs. having it defined outside? For example:

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
  }

  ...
}

vs.

func SomeFunc(b []byte) error {

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

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

  ...
}

Would there be any situations where one is preferred over the other?


There is no performance difference – it's only a difference of scope (ie, where the type definition can be seen). If you only need the type within a single function, it's fine to define it there.

As others have noted, if you define a type at the package level (ie, outside of a function) with a name beginning with a capital letter, it will be exported (ie, visible outside the package). If the name doesn't begin with a capital letter, it will only be visible within the package.


My understanding is the difference is just in accessibility. A struct defined starting with an upper case letter will be exportable, meaning it can be accessed from other packages. A struct defined starting with a lower case letter can be accessed from anything within the same package but not externally. A struct defined in a function in line can only be accessed/initialized by that function.


There is the obvious concern of scoping when declaring anything within a function body as opposed to outside of it.

But also in your first example you are declaring a type outside of the function body denoted by the symbol Outside.

In your second example you are declaring a variable denoted by the symbol inside. This has a literal type of the struct you have described.

Note that in the first example you can use the symbol Outside to refer to any variables that are of type Outside.

In your second example, there is no symbol to refer to type of the variable called inside. This is because the type of this variable is denoted using an anonymous struct.

链接地址: http://www.djcxy.com/p/38362.html

上一篇: Azure IoT Hub,EventHub和函数

下一篇: 在函数内部和外部定义结构的含义?