type gasEngine struct { mpg uint8 gallons uint8}func main() { var myEngine gasEngine // myEngine = {mpg:0, gallons: 0} var myEngine2 gasEngine{mpg:25, gallons:15} // similar to a constructor var myEngine3 gasEngine{25, 15} // myEngine3 = {mpg:25, gallons: 15} // OR myEngine.mpg = 20}
We can also encapsulate another struct in our gasEngine struct, such as an Owner type
type gasEngine struct { mpg uint8 gallons uint8 ownerInfo owner}type owner struct { name string}// Above has {mpg: 25, gallons: 15, ownerInfo.anme: "alex"}// OR we can also do the following belowtype gasEngine struct { mpg uint8 gallons uint8 owner}type owner struct { name string}// Then the above will have a field for gasEngine called gasEngine.name
We can also do this for int, then the gasEngine struct will have a field name called int
Anonymous structs
Methods in structs
type gasEngine struct { mpg uint8 gallons uint8}func (e gasEngine) milesLeft() uint8 { // assigns this method to gasEngine struct return e.gallons*e.mpg}
Interface
Similar to a struct, but helps us define a more general struct
type engine interface { milesLeft() uint8}
We can then use this interface in method parameters, so that the method can take in any struct that has implemented the mileLeft() method