4

I know about struct embedding

type newType struct {someStruct}

I know about type aliasing:

type newType = someStruct

But is there any practical reason to use

type newType someStruct

What about primitive types?

type newType int

What is the right name for such a definition?

1
  • 2
    It's a type definition, it doesn't have any other name as far as I know. It allows you to easily define a type that has the same structure, or memory layout as the one you're referencing in the definition. Commented Apr 25, 2019 at 20:30

2 Answers 2

7

Naming: All of the snippets are type declarations. One of the declarations is a type alias (the one with the =). The remaining declarations are type definitions. The first of those definitions uses a struct with an embedded field.

The code type newType someStruct is useful when one wants to define a new type with the same memory layout as some other struct type. This might because the programmer wants to use different methods on the same memory layout.

The code type newType int is useful for defining a type with a semantic difference from int or for attaching methods to the primitive type. See reflect.Kind for one example.

Sign up to request clarification or add additional context in comments.

1 Comment

Two main reasons for the last case: 1) to define a semantic difference between two memory-equivalent types (e.g. rune vs int32), or 2) to define different method sets on two memory-equivalent types; though 1 without 2 is not uncommon, 2 without 1 is.
1

struct embedding vs “aliasing”


You are conflating to different constructs.

For the definition of struct embedding, see The Go Programming Language Specification.


Here's an explanation of and the rationale for Go type aliases.

Go 1.9 Release Notes (released 2017/08/24)

Changes to the language

Go now supports type aliases to support gradual code repair while moving a type between packages. The type alias design document and an article on refactoring cover the problem in detail. In short, a type alias declaration has the form:

type T1 = T2

This declaration introduces an alias name T1—an alternate spelling—for the type denoted by T2; that is, both T1 and T2 denote the same type.


Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.