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!!!
  • 相关阅读:
    POJ 2503 Babelfish
    POJ 1182 食物链
    POJ 2352 Stars
    POJ 2528 Mayor's posters
    POJ 1328 Radar Installation
    POJ 1017 Packets
    jQuery实现登录提示
    【1-5】jQuery对象和DOM对象
    【1-4】jQuery代码风格-导航栏
    【3】买苹果
  • 原文地址:https://www.cnblogs.com/hbhb/p/15020304.html
Copyright © 2011-2022 走看看