Performance difference of type definitions

Go has two ways to define a new type based on another type:

type String string
type String struct { string }

Does one definition have a bigger runtime or memory overhead than the other?

You are defining completely different things. And there is a third option - I will list them all:

type String = string // will define a type alias
// It has the same memory layout and same type information
// The alias can be used as string without conversion everywhere

type String string // will define a new type which is as string
// It has the same memory layout, but different type information
// The type needs to be cast to string to use it as a string

type String struct {string} // will define a new struct-type
// The type will look like this: {string: string}
// It has the same memory layout, but different type information
// The type needs to be converted to string to use it as a string

Since they all share the same memory layout and size, the only performance differences will come from compiler optimizations, which will probably be better suited for a type alias or simple type without struct.

Example Code on Go Playground

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.