0

This is code from Golang Tutorial : Go Full Course at 2:37:32

I cannot understand what he mean when using .(Cat) on kitty

Is he kind of type casting or something on the kitty interface to Cat type?(IDK what I am talking, please help)

Please share a link to the documentation if possible

var kitty2 Cat = kitty.(Cat)
package main

type Cat string

type Animal interface {
    happy() string
    sad() string
}

func (c Cat) happy() string {
    return "haha"
}

func (c Cat) sad() string {
    return ":("
}

func main() {
    var kitty Animal
    kitty = Cat("kitty")
    var kitty2 Cat = kitty.(Cat)
}

1 Answers1

-1

It is an attempt to type cast. Take a look at this lesson in the tour If they had done the following then you can use to variable ok to check if the type casting worked, here ok is of type bool

kitty, ok := kitty.(Cat)
Alwin Doss
  • 962
  • 2
  • 16
  • 33
  • 1
    There are no type cast in Go and you cannot attempt one. – Volker Aug 26 '22 at 14:25
  • @Volker so what is happening there? – Alwin Doss Aug 28 '22 at 13:02
  • A type assertion. – Volker Aug 28 '22 at 14:12
  • @Volker okay. So what does the variable `kitty` on the left hand side have? – Alwin Doss Aug 29 '22 at 09:24
  • It depends solely on the value of kitty on the right hand side. Note that your code redeclares kitty which is a bad practice. It's a matter of fact that there _are_ no casts in Go and neither a type conversion nor a type assertion are "casts" (which has a defined meaning for languages with C heritage). – Volker Aug 29 '22 at 09:38
  • @Volker in this example above the variable `kitty` is assigned to the value of type `Cat`. I do understand the Go in none of its documentation uses the the phrase type casting, but the principle is here. – Alwin Doss Aug 30 '22 at 05:08
  • "the variable kitty is assigned to the value of type Cat" is a false statement as it doesn't describe what happens. This might be a simple language problem. I prefer the language used in the language spec, the Tour of Go, and the official documentation. Please note that the principle of a type cast is _not_ present in Go, it was a deliberate design choice _not_ to allow type cast. And IMHO it is _not_ _helpful_ to talk about "type casts". Type conversions and type assertions are different and calling both a "type cast" blurs their difference. – Volker Aug 30 '22 at 05:18