Nivelle 开拓视野冲破艰险看见世界 身临其境贴近彼此感受生活

go学习第三篇(函数,接口)

2018-09-01
go

函数

func function_name( [parameter list] ) [return_types]
{
   函数体
}


返回多个值:

package main

import "fmt"

func swap(x string, y string) (string, string) {
	return y, x
}

func main() {
	a, b := swap("nivelle", "suyao")
	fmt.Println(a, b)
}

值传递,引用传递

package main

import "fmt"

func swap(x, y int) int {
	var temp int

	temp = x
	x = y
	y = temp
	fmt.Printf("作为行参的时候的值a= %d,b = %d", x, y)
	fmt.Println()
	return temp
}

func main() {
	var a int = 100
	var b int = 200

	fmt.Printf("交换前 a= %d,b = %d", a, b)

	fmt.Println()

	swap(a, b)

	fmt.Printf("交换后 a= %d,b = %d", a, b)

}


结果:

交换前 a= 100,b = 200
作为行参的时候的值a= 200,b = 100
交换后 a= 100,b = 200

package main

import "fmt"

func swap(x *int, y *int) {
	var temp int
	temp = *x /* 保存 x 地址上的值 */
	*x = *y   /* 将 y 值赋给 x */
	*y = temp /* 将 temp 值赋给 y */
}

func main() {
	var a int = 100
	var b int = 200

	fmt.Printf("交换前 a= %d,b = %d", a, b)

	fmt.Println()

	swap(&a, &b)

	fmt.Printf("交换后 a= %d,b = %d", a, b)

}


结果:

交换前 a= 100,b = 200
交换后 a= 200,b = 100

接口定义和使用

/* 定义接口 */
type interface_name interface {
   method_name1 [return_type]
   method_name2 [return_type]
   method_name3 [return_type]
   ...
   method_namen [return_type]
}

/* 定义结构体 */
type struct_name struct {
   /* variables */
}

/* 实现接口方法 */
func (struct_name_variable struct_name) method_name1() [return_type] {
   /* 方法实现 */
}


package main

import (
	"errors"
	"fmt"
)

type User struct {
	name string
	age  int
}

type UserService interface {
	getUserById(id int) (User, error)
}

type UserServiceImpl struct {
}

func (a UserServiceImpl) getUserById(id int) (User, error) {
	fmt.Println("getUserById")
	return User{"name", 123}, errors.New("go is an advanced language")
}

func main() {
	var userService UserService
	userService = new(UserServiceImpl)
	u, error := userService.getUserById(1)
	if error != nil {
		fmt.Println(error)
	}
	fmt.Println(u)
}



结果:

getUserById
go is an advanced language
{name 123}


评论