Home > Software design >  When to use unnamed type?
When to use unnamed type?

Time:03-31

Read the answer

We use named struct type, say,

type Foo struct{
   name string
   email string
}

var y Foo

to decode the data coming on wire or introduce a new type that holds set of values and operations on those values


  1. When to use unnamed type?

              var x struct{
                  name string
                  email string
               }
    
  2. What is the syntax to initialize variable identifier x?

CodePudding user response:

As a quick rule, if you ever find yourself copying/typing out the struct definition again, you may as well make it a named type. That is the whole point of names, after all; they are a shortcut to refer to the same thing multiple times. To avoid naming clutter, try to declare the type in the narrowest scope possible (for example, within the function scope where it is used).


The syntax to initialize is as follows:

var x struct{
    name string
    email string
} = struct {
    name  string
    email string
}{
    name: "name", 
    email: "email",
}

which can be shortened to

var x = struct {
    name  string
    email string
}{
    name:  "name",
    email: "email",
}

since the type can be inferred.

The best time to use unnamed types is when you do not have to explicitly refer to the type again. Since the type has no name, to refer to it explicitly you (generally) have to duplicate the whole type specification again. For example, when assigning a new value.

// reassign x
x = struct {
    name  string
    email string
}{
    name:  "name2",
    email: "email2",
}

This will quickly get quite ugly, especially for larger structs, and duplicated code creates duplicated work when it needs to be updated.

You could attempt to shorten this as follows:

// reassign x
x.name = "name2"
x.email = "email2"

This should be considered bad form, however, as it is unclear if/that the intent was to reassign the entire value of "x" or just alter some select fields. If the struct is updated to add more fields, then this code may become incorrect without warning.

  • Related