-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?

2
  • 4
    There is no inheretence in Go, so there's no such thing as "Go inheritance syntax" Feb 12, 2021 at 8:29
  • Good to know that there is no inheritance in Go. Sorry for the inappropriate title, but I will leave it for lesson.
    – KinoP
    Feb 12, 2021 at 8:31

1 Answer 1

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())
2
  • 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, 2021 at 8:26
  • 1
    @aureliar Done, was still editing the answer.
    – icza
    Feb 12, 2021 at 8:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.