Question

In Go, is type Txt string simply a shortcut for type Txt struct {string}?

Was it helpful?

Solution

The answers to all your questions is a loud "No!".

  1. Embedding a string into a struct is basically a useless example of embedding as string has no methods which could get promoted to the embedding type.

  2. The construct type Txt string defines a new type named Txt and the underlying type is a string. Txt has different method set as it is a different type. But as its underlying type is string you may freely type convert them.

  3. type T string is not a shortcut for type S struct { string }, e.g. you cannot do t := T{"foo"}, only t := T("foo") works and for S it is the other way around.

  4. Embedding has absolutely no relation to inheritance. These are two different things. Mimicking inheritance with embedding is doomed to fail as you cannot do inheritance in Go. (This is a general advice, it is a very useful advice; but some specific inheritance problems might be doable with embedding. Just forget about inheritance and you will be happier.)

  5. Embedding is useful if two types have common data and methods in which case embedding provides some nice syntactic sugar: Instead of type T struct { c common; r rest }; t := T{...}; t.common.method() you can do type T struct { common; r rest }; t := T{...}; t.method() which saves typing but is basically the same code. Package testing contains nice examples.

OTHER TIPS

No

type Txt string
type StringStruct struct {
    string
}

func main() {
    var txt Txt = "abc"
    fmt.Println(len(txt))

    var str string = "abc"
    fmt.Println(len(str))

    // Uncomment me to get a compiler error!
    /* var ss StringStruct = StringStruct{"abc"}
    fmt.Println(len(ss)) */
}

You can't call len on the embedded one. You have to call len(ss.string), thus it's safe to say that type Txt string is not shorthand for type Txt struct{ string }.

No,string is a native type, like int, uint, float, etc.

Internally it's a slice of sorts.

Quoting http://blog.golang.org/strings

In Go, a string is in effect a read-only slice of bytes.

It's important to state right up front that a string holds arbitrary bytes. It is not required to hold Unicode text, UTF-8 text, or any other predefined format. As far as the content of a string is concerned, it is exactly equivalent to a slice of bytes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top