Creating Custom Data Types with Go Flashcards
When is it recommended to use pointer references even on read only methods?
When the struct is huge and you don’t want to have multiple copies of the given structure
What if I use one reference in a method on a file with multiple methods, what is recommended next?
Make all methods to use references to keep consistency.
How to declare a string alias? When is it useful?
type MyString = string
To facilitate the reading of our code
“Inherits” all fields and methods.
What is a type definition declaration? What it defers from an alias? How to declare?
Is actually creating a new type from golang’s perspective.
Type definition declaration allows creating extension methods over the new type (while the alias won’t allow). Need casts to the original type (alias were simpler in this case)
type MyString string
What is an embedded type? How to declare?
Is embedding all fields and methods from a struct into the new struct (without having to access it as struct1.struct2.name.
type Person struct {
Name
}
Can I embed interfaces into structs?
yes
What happens if my struct is embedded with two interfaces that has the same name?
it will conflict… you can implement the second interface specific’s signature.
Can I compare two instances of the same struct? What happens If I have complex types such as array and func?
It is going to compare the contents of the struct normally. Will no longer be able to compare.
How does interface equality work? What if it has complex types, will the compiler allow? What about the runtime?
Same interface types with the same content are equal.
Compiler allows but runtime it’ll panic.
How to create a custom comparer?
Create an extension with the Equals keyword (but you still need to call equalls manually)
Does go automatically cast our interface type when using inside an switch (if the switch has a type condition, e.g: case string:)? Is it the same for structs?
yes. yes