惜风不起、唯有努力!
golang中的interface普通传参,返回,指针简单使用

golang中的interface普通传参,返回,指针简单使用

package main

import (
	"fmt"
	"log"
)

type Cat interface {
	GetInfo() (string, error)
	Echo(num int)
}

type Info struct {
	Name  string
	Age   int
	Hobby string
}

type Language struct {
	Msg string
}

func (i Info) GetInfo() (string, error) {
	if i.Name == "tom"{
		i.Name = "alis"
		i.Age = 3
	}
	fmt.Println(i.Name, i.Age, i.Hobby)
	return "ok", nil
}

func (l Language) Echo(n int) {
	fmt.Println(l.Msg,"---> ", n)
}


func main(){
	g := Info{
		Name: "tom",
		Age: 2,
		Hobby: "吃鱼",
	}
	c, err := g.GetInfo()
	if err != nil {
		log.Fatal("GetInfo方法调用出错!")
	}else {
		fmt.Println(c)
	}
	
	s := Language{
		Msg: "我是一只汤姆猫,喜欢吃鱼!",
	}
	s.Echo(2023)
}

指针

package main

import (
	"fmt"
)

var	mapStr = map[int]string{
		0: "零",
		1: "一",
		2: "二",
		3: "三",
		4: "四",
}

type Cat interface {
	Echo(num int)
}

type Test struct{
	T string
	S int
}

type Language struct {
	Msg string
	MsgList []string
	MsgMap map[int]string
	MsgTest *Test
}

func (l Language) Echo(n int) {
	fmt.Println(l.Msg,"---> ", n)
	fmt.Println(l.MsgList)
	for k, v := range l.MsgMap {
		fmt.Printf("map key --> %d\n", k)
		fmt.Printf("map value --> %s\n", v)
	}
	fmt.Println(l.MsgTest.S)
}

func main(){
	
	language := Language{
		Msg: "我是一只汤姆猫,喜欢吃鱼!",
		MsgList: []string{"金丝虎", "踏雪银白"},
		MsgMap: mapStr,
		MsgTest: &Test{
			T: "test",
			S: 2023,
		},
	}
	language.Echo(2023)
}

发表回复

您的电子邮箱地址不会被公开。