首页 > 其他分享 >0092-Go-方法

0092-Go-方法

时间:2022-10-30 08:34:10浏览次数:72  
标签:perim area fmt height width Go 方法 0092 rect

环境

  • Time 2022-08-24
  • Go 1.19

前言

说明

参考:https://gobyexample.com/methods

目标

使用 Go 语言的方法。

值方法

package main

import "fmt"

type rect struct {
    width, height int
}

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

func main() {
    r := rect{width: 10, height: 5}

    fmt.Println("perim:", r.perim())
    // 指针也可以调用值方法
    rp := &r
    fmt.Println("perim:", rp.perim())
}

指针方法

package main

import "fmt"

type rect struct {
    width, height int
}

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

func main() {
    r := rect{width: 10, height: 5}
    // 值可以直接调用指针方法
    fmt.Println("area: ", r.area())

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

总结

使用 Go 语言的方法。

附录

标签:perim,area,fmt,height,width,Go,方法,0092,rect
From: https://www.cnblogs.com/jiangbo4444/p/16840462.html

相关文章

  • 0093-Go-接口
    环境Time2022-08-24Go1.19前言说明参考:https://gobyexample.com/interfaces目标使用Go语言的接口。定义接口typegeometryinterface{area()float64......
  • 0094-Go-结构体嵌入
    环境Time2022-08-24Go1.19前言说明参考:https://gobyexample.com/struct-embedding目标使用Go语言的结构体嵌入。定义结构体typebasestruct{numint......
  • 0095-Go-泛型
    环境Time2022-08-24Go1.19前言说明参考:https://gobyexample.com/generics目标使用Go语言的泛型。泛型函数packagemainimport"fmt"funcMapKeys[Kcom......
  • 0075-Go-变量
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/variables目标使用Go语言变量的申明和使用变量。示例packagemainimport"fmt"funcma......
  • 0076-Go-常量
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/constants目标使用Go语言的常量。示例packagemainimport("fmt""math")co......
  • 0077-Go-for 循环
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/for目标使用Go语言的for循环。单条件循环类似其它语言中的while循环。packagemain......
  • 0078-Go-if else 条件判断
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/if-else目标使用Go语言的if/else条件判断。条件判断条件判断的小括号可以省略,但是后面的......
  • 0079-Go-switch 分支
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/switch目标使用Go语言的switch分支语句。整数分支packagemainimport"fmt"funcmai......
  • 0080-Go-数组
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/arrays目标使用Go语言的数组。申明数组packagemainimport"fmt"funcmain(){v......
  • 0081-Go-切片 slice
    环境Time2022-08-23Go1.19前言说明参考:https://gobyexample.com/slices目标使用Go语言的切片类型。新建切片类型packagemainimport"fmt"funcmain()......