Go语言中type的用法

Go语言中type的用法:

1.定义结构体类型
2.类型别名
3.定义接口类型
4.定义函数类型

1.定义结构体类型

结构体可用于用户自定义数据类型和进行面向对象编程。

type Person struct {
        name string
        age int
        sex bool
}
func (p *Person)Eat(){
    fmt.Printf("%s爱吃西红柿炒鸡蛋
",p.name)
}
func (p *Person)Drink(){
    fmt.Printf("%s爱喝可乐
",p.name)
}
func (p *Person)Sleep(){
    fmt.Printf("%s要睡8个小时
",p.name)
}
func (p *Person)Love(){
    fmt.Printf("%s喜欢
",p.name)
}

  

2.类型别名

type str string
str类型与string类型等价
例子:

package main

import "fmt"

type str string
func main () {
    var myname str = "Ling"
    fmt.Printf("%s",myname)
}


3.定义接口

type Shaper interface {
    Area() float64
}

接口定义了一个 方法的集合,但是这些方法不包含实现代码,它们是抽象的,接口里也不能包含变量。
注意实现接口可以是结构体类型,也可以是函数类型


4.定义函数类型

当不定义函数类型,传递函数时:

package main

import "fmt"

func isOdd(integer int) bool {
    if integer%2 == 0 {
        return false
    }
    return true
}

func isEven(integer int) bool {
    if integer%2 == 0 {
        return true
    }
    return false
}

func filter(slice []int, f func(int) bool) []int {
    var result []int
    for _, value := range slice {
        if f(value) {
            result = append(result, value)
        }
    }
    return result
}

func test(){
        slice := []int {1, 2, 3, 4, 5, 7}
        fmt.Println("slice = ", slice)
        odd_res := filter(slice, isOdd)    // 函数当做值来传递了
        fmt.Println("Odd elements of slice are: ", odd_res)
        even_res := filter(slice, isEven)  // 函数当做值来传递了
        fmt.Println("Even elements of slice are: ", even_res)
}
func main(){
    test()
}

当定义函数类型,传递函数时:

package main

import "fmt"

type functinTyoe func(int) bool // 声明了一个函数类型

func isOdd(integer int) bool {
    if integer%2 == 0 {
        return false
    }
    return true
}

func isEven(integer int) bool {
    if integer%2 == 0 {
        return true
    }
    return false
}

// 声明的函数类型在这个地方当做了一个参数
func filter(slice []int, f functinTyoe) []int {
    var result []int
    for _, value := range slice {
        if f(value) {
            result = append(result, value)
        }
    }
    return result
}

func test(){
        slice := []int {1, 2, 3, 4, 5, 7}
        fmt.Println("slice = ", slice)
        odd_res := filter(slice, isOdd)    // 函数当做值来传递了
        fmt.Println("Odd elements of slice are: ", odd_res)
        even_res := filter(slice, isEven)  // 函数当做值来传递了
        fmt.Println("Even elements of slice are: ", even_res)
}
func main(){
    test()

原文地址:https://www.cnblogs.com/-wenli/p/12304379.html