Reputation: 9652
In Go, is type Txt string
simply a shortcut for type Txt struct {string}
?
Upvotes: 1
Views: 139
Reputation: 42486
The answers to all your questions is a loud "No!".
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.
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.
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.
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.)
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.
Upvotes: 7
Reputation: 22236
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 }
.
Upvotes: 4
Reputation: 99411
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.
Upvotes: 2