zoukankan      html  css  js  c++  java
  • go函数、方法、接口笔记

    函数

    //模板
    func 函数名(参数1,……)(返回值1,……){
      doSomething
    }
    //例子
    func PrintInt(a int) int {
      fmt.Println(a)
      return 0
    }

    方法

    //模板
    func (主人名 类型)方法名(参数列表)(返回值列表){
      doSomething
    }
    
    go语言的方法与函数不一样 从上模板定义可以看到多了(主人名 类型)
    方法和函数的最大区别是方法有接收者(从属),即方法都是有主人的
    
    我的理解java区别是 
    java中方法写在需要调用的对象中 如person类的run()方法写在peron对象中 
    而go是哪个类想调peron对象的run()方法就在该类中新建一个run() 方法写在里面 再定义个从属(主人名 类型)
    可能go不是面向对象的思想
    
    
    //例子
    // 定义结构体
    type person struct {
      name   string
      age    int
      gender string
    }
    // 定义方法
    func (p *person) describe() {
      fmt.Printf("%v is %v years old.", p.name, p.age)
    }
    func (p *person) setAge(age int) {
      p.age = age
    }
     
    func main() {
      pp := &person{name: "Bob", age: 42, gender: "Male"}  
      // 使用 . 来调用方法 
      pp.describe()
      // => Bob is 42 years old
      pp.setAge(45)
      fmt.Println(pp.age)
      //=> 45
    }

    接口

    //例子
    package main
     
    import (
      "fmt"
    )
     
    type animal interface {
      description() string
    }
     
    type cat struct {
      Type  string
      Sound string
    }
     
    type snake struct {
      Type      string
      Poisonous bool
    }
     
    func (s snake) description() string {
      return fmt.Sprintf("Poisonous: %v", s.Poisonous)
    }
     
    func (c cat) description() string {
      return fmt.Sprintf("Sound: %v", c.Sound)
    }
     
    func main() {
      var a animal
      a = snake{Poisonous: true}
      fmt.Println(a.description())
      a = cat{Sound: "Meow!!!"}
      fmt.Println(a.description())
    }
     
    //=> Poisonous: true
    //=> Sound: Meow!!!
  • 相关阅读:
    innodb force recovery
    date 获取昨天日期
    Mysql slave 状态之Seconds_Behind_Master
    shell编程——if语句 if -z -n -f -eq -ne -lt
    shell判断条件是否存在
    linux shell if 参数
    MYSQL使用二进制日志来恢复数据
    linux下nagios的安装与部署
    mysql slave 错误解决
    LODS LODSB LODSW LODSD 例子【载入串指令】
  • 原文地址:https://www.cnblogs.com/hbhb/p/15020304.html
Copyright © 2011-2022 走看看