methods for struct _ golang

Go supports methods defined on struct types

package main

import (
    "fmt"
)

type rect struct {
    width, height int
}

func (r *rect) area() int {
    return r.width * r.height
}

func (r rect) perim() int {
    return 2*r.width + 2*r.height
}

func main() {

    r := rect{width: 10, height: 5}

    fmt.Println("area : ", r.area())
    fmt.Println("perim : ", r.perim())

    rp := &r
    fmt.Println("area : ", rp.area())
    fmt.Println("perim : ", rp.perim())
}
area :  50
perim :  30
area :  50
perim :  30

总结 :

  1 : struct 的指针也能直接引用 struct 的方法

时间: 2024-11-08 23:42:06

methods for struct _ golang的相关文章

errors _ golang

In Go it's idiomatic to communicate errors via an explicit, separate return value. this constrasts errors via an explicit, separate return value. This constrasts with the exceptions used in languages like Java and Ruby and the overloaded single resul

interface _ golang

Interfaces are named collections of methods signatures package main import ( "fmt" "math" ) type geometry interface { area() float64 perim() float64 } type square struct { width, height float64 } type circle struct { radius float64 } f

multiple return values _ golang

Go has built-in support for multiple return values. This feature is used often in idiomatic Go, for example to return both result and error values from a function package main import ( "fmt" ) func vals() (int, int) { return 3, 7 } func main() {

structs _ golang

Go's structs are typed collections of fields. They're useful for grouping data together to form records package main import ( "fmt" ) type person struct { name string age int } func main() { fmt.Println(person{"Bob", 20}) fmt.Println(p

variadic function _ golang

Variadic functions can be called with any number of trailing arguments. For example, fmt.Println is a common variadic function package main import ( "fmt" ) func sum(nums ...int) { fmt.Println(nums, " ") total := 0 for _, num := range

if else _ golang

if else 在 golang package main import ( "fmt" ) func main() { if 7%2 == 0 { fmt.Println("7 is even") } else { fmt.Println("7 is odd") } if 8%4 == 0 { fmt.Println("8 is divisible by 4") } if num := 9; num < 0 { fmt

for _ golang

for 是 golang 唯一的 looping 结构, package main import ( "fmt" ) func main() { i := 1 for i <= 3 { fmt.Println(i) i += 1 } for j := 7; j <= 9; j++ { fmt.Println(j) } for { fmt.Println("loop") break } } 1 2 3 7 8 9 loop 总结 : 对于这个, 额, 我觉

constants _ golang

golang 中支持 长量 const or static package main import ( "fmt" "math" ) const s string = "constant" const a = 3000 func main() { const s = 3000 fmt.Println(s) const n = (3e8 / s) fmt.Println(n) fmt.Println(int64(n)) fmt.Println(ma

statefule goroutines _ golang

In the previous example we used explicit locking with mutexes to synchronize access to shared state across multiple goroutines. Another option is to use the built-in synchronization features of goroutines and channels to achieve the same result. This