zoukankan      html  css  js  c++  java
  • Golang之方法(自定义类型,struct)

    方法的使用,请看本天师的代码

    //Golang的方法定义
    //Golang中的方法是作用在特定类型的变量上,因此自定义类型,都可以有方法,不仅仅是struct
    //定义:func (recevier type) methodName(参数列表)(返回值列表){}
    //方法和函数的区别
    /*
    1,函数调用:function(variable,参数列表)
    2, 方法,variable.function(参数列表)
    方法的控制,通过大小写空格控制
     */

    。。。。

    package main
    
    //Golang的方法定义
    //Golang中的方法是作用在特定类型的变量上,因此自定义类型,都可以有方法,不仅仅是struct
    //定义:func (recevier type) methodName(参数列表)(返回值列表){}
    import "fmt"
    
    type integer int
    
    func (p integer) print() {
        fmt.Println("p is:", p)
    }
    //这里传递的是副本,想改变p的值,需要传递指针
    func (p *integer) set(b integer) {
        *p = b
    }
    
    type Student struct {
        Name  string
        Age   int
        Score int
        sex   int
    }
    
    //这里需要接受指针 *Student(接收者),否则修改不了值
    func (p *Student) init(name string, age int, score int) {
        p.Name = name
        p.Age = age
        p.Score = score
        fmt.Println(p)
    }
    func (p Student) get() Student {
        return p
    }
    
    func main() {
        var stu Student
        //修改地址的写法(&stu).init
        //但是go可以自动知道,接受者是指针,这里stu就传递地址
        stu.init("stu", 18, 99)
        stu1 := stu.get()
        fmt.Println(stu1)
    
        //type integer方法
        var a integer
        a = 100
        a.print()
        a.set(1000)
        a.print()
    }
  • 相关阅读:
    公司技术部与其他部门之间的那些事儿
    5万元百元大钞的"渣渣钱"重新拼接的软件方面的解决办法的思路。
    公司技术部门内部的发展变化过程。
    手机开发与360的那点事儿
    通用快排
    被中断的函数
    setjmp与longjmp
    setjmp在非主函数中调用
    array and structure
    check your input
  • 原文地址:https://www.cnblogs.com/pyyu/p/8258133.html
Copyright © 2011-2022 走看看