Golang custom type and type alias

type myInt int32type myInt = int32Not the same concept as

  1. Custom type:type myInt int32

    A type defined in this way is an entirely new type that int32has the same underlying structure as but is int32not compatible with the type.

    type myInt int32
    
    var a int32 = 5
    var b myInt = a  // 这里会产生编译错误
    

    Although myIntthe underlying types of are int32, they are distinct in the type system.

  2. Type aliases:type myInt = int32

    Type aliasing is to give an existing type a new name that is exactly the same as the original type in the type system.

    type myInt = int32
    
    var a int32 = 5
    var b myInt = a  // 这里不会产生编译错误
    

    Here myIntis int32an alias for , so no compile errors will be generated.

  3. Summarize

    • A custom type creates an entirely new type that is incompatible with the original type in the type system.

    • A type alias simply gives an existing type a new name that is exactly the same as the original type in the type system.

    • Custom types can be used for encapsulation or abstraction, and type aliases can be used to ensure backward compatibility or to simplify type names.

    By understanding these differences, you can use Go's type system more flexibly to meet various programming needs.

Guess you like

Origin blog.csdn.net/qq_35760825/article/details/132282965