A Go nyelv nem klasszikus értelemben vett objektum-orientált nyelv, de használhatunk benne struktúrákat, beágyazásokat, és interfészeket. Ezek lehetővé teszik az objektum-orientált programozás néhány jellemzőjének használatát.
package main import ( "fmt" ) type Employee struct { Name string City string Salary float32 } func main() { emp := Employee{ Name: "Beker", City: "Budapest", Salary: 1000, } fmt.Println(emp.Name, emp.City, emp.Salary) }
package main import ( "fmt" ) type Employee struct { Name string City string Salary float32 } func (e Employee) print() { fmt.Println(e.Name, e.City, e.Salary) } func main() { emp := Employee{ Name: "Beker", City: "Budapest", Salary: 1000, } emp.print() }
package main import ( "fmt" ) type Address struct { City string Street string } type Employee struct { Name string Address Salary float32 } func (e Employee) print() { fmt.Println(e.Name, Address{e.City, e.Street}, e.Salary) } func main() { emp := Employee{ Name: "Erős Istávn", Address: Address{"Szeged", "Kék utca"}, Salary: 395, } emp.print() }
package main import ( "fmt" ) type Person interface { Rest() } type Employee struct{} func (e Employee) Rest() { fmt.Println("Pihenés...") } func main() { emp := Employee{} emp.Rest() }
package main import ( "fmt" ) type Person interface { Rest() } type Employee struct{} func (e Employee) Rest() { fmt.Println("Pihenés...") } /* Egy fügvény ami bármilyen Struktúrát elfogad ami implementálja a Person interfészt */ func Resting(p Person) { p.Rest() } func main() { emp := Employee{} Resting(emp) }