-1

In Go what is the difference below?

I tried to search, but I couldn't think of a right term to describe them. How are they officially called?

#1 - Parent inside struct:

type MyTime struct {
    time.Time
}

#2 - Parent right after my type without struct definition:

type MyTime time.Time

For #2, I can initialize my type with another time.Time like mt := MyTime(t). How to initialize #1 type with another time.Time variable?

KinoP
  • 1,532
  • 15
  • 23

1 Answers1

5

Go is not an object oriented language, there is no type hierarchy and inheritance. For details, see What is the idiomatic way in Go to create a complex hierarchy of structs? and Go embedded struct call child method instead parent method.

Your first example creates a new type MyTime embedding time.Time. By embedding a type, all fields and methods of the embedded type gets promoted and are available as if they were fields or methods of the embedder type, very handy when you want to implement an interface for example (because the promoted methods will "exist" without having to declare them).

You can instantiate it like (for details, see Golang embedded struct type):

t := MyTime{Time: time.Now()}

Your second example creates a new type, all methods will be stripped from it. This comes handy when you do not want the existing methods to be part of the new type. A shining example of this is to define the String() method or override marshaling behavior when you want to call the original behavior in your implementation, for details see Call json.Unmarshal inside UnmarshalJSON function without causing stack overflow. You can create a value of it using a simple type conversion:

t := MyTime(time.Now())
icza
  • 389,944
  • 63
  • 907
  • 827
  • It may be worth to add that there is no inheritance in Go. It is possible to approach some properties by using type embedding, but that's all. – aureliar Feb 12 '21 at 08:26
  • 1
    @aureliar Done, was still editing the answer. – icza Feb 12 '21 at 08:31