函数
package main
import "fmt"
func add(a int, b int) (int, error) {
return a + b, nil
}
func add2(a int, b int) (sum int, err error) {
sum = a + b
err = nil
return sum, err
}
// 参数数量任意
func add3(items ...int) (sum int) {
for _, value := range items {
sum += value
}
return sum
}
//函数是一等公民,可以作为变量、参数
// 闭包:可以随时归零,而且不需要全局变量
func autoIncrement() func() int {
local := 0
return func() int {
local += 1
return local
}
}
func main() {
sum := add3(1, 2, 3)
fmt.Println(sum)
//闭包
next := autoIncrement()
for i := 0; i < 5; i++ {
fmt.Print(next()) //1,2,3,4,5
}
fmt.Println()
next2 := autoIncrement()
for i := 0; i < 3; i++ {
fmt.Print(next2()) //1,2,3
}
}
defer
package main
import (
"fmt"
"sync"
)
func deferReturn() (ret int) {
defer func() {
ret++
}()
return 10
}
func main() {
var mu sync.Mutex
mu.Lock()
defer mu.Unlock() //defer语句在return之前才执行
//defer执行的顺序为栈的顺序,LIFO
defer fmt.Println("1")
defer fmt.Println("2")
ret := deferReturn()
fmt.Println(ret)//11,defer有能力改变返回值
}
panic、recover
package main
import "fmt"
func main() {
defer func() {
r := recover()
if r != nil {
fmt.Println("recover!!!")//捕获panic
}
}()
panic("panic!!!") //直接导致程序退出
fmt.Println("1")
}
结构体
package main
import "fmt"
type Person struct {
name string
age int
address string
height float32
}
func (p Person) print() {
fmt.Printf("name:%s, age:%d", p.name, p.age)
fmt.Println()
}
type Student struct {
p Person
score float32
}
type Student2 struct {
Person
score float32
}
func main() {
type myInt2 = int //类型别名
type myInt int //自定义类型,不可加法,可扩展
//初始化
p1 := Person{"neo", 18, "mooc", 1.80}
p2 := Person{
name: "harry",
address: "beijing",
}
var p3 Person
p3.age = 20
p3.print()
//匿名结构体:一次性
address := struct {
province string
city string
}{
province: "beijing1",
city: "beijing2",
}
fmt.Println(address)
//结构数组
pp3 := []Person{
{name: "potter"},
{name: "peter"},
}
fmt.Println(p1)
fmt.Println(p2)
fmt.Println(pp3)
//嵌套结构体
s := Student{Person{name: "neo", age: 18}, 99}
s.p.height = 1.80
s1 := Student{}
s1.p.name = "neo"
s2 := Student2{}
s2.name = "neo"
}
指针
package main
import "fmt"
type Person2 struct {
name string
}
func main() {
po := &Person2{
name: "neo",
}
//以下在go中等效
po.name = "leo"
(*po).name = "neo"
//初始化
var pp = new(Person2)
fmt.Println(pp.name)
//nil的用法
var m1 map[string]string
var m2 = make(map[string]string, 0)
//m1["name"] = "harry" //报错
m2["name"] = "potter" //不报错,建议用make
for key, value := range m1 {
fmt.Println(key, value)
}
for key, value := range m2 {
fmt.Println(key, value)
}
}
interface
定义
package main
import "fmt"
// 接口定义
type Duck interface {
Gaga()
Walk()
Swim()
}
// 自定义类用于接口实现
type pskDuck struct {
legs int
}
func (pd *pskDuck) Gaga() {
fmt.Println("Gaga")
}
func (pd *pskDuck) Walk() {
fmt.Println("walking")
}
func (pd *pskDuck) Swim() {
fmt.Println("swim")
}
func main() {
var d Duck = &pskDuck{}
d.Walk()
}
多接口
package main
import "fmt"
type MyWriter interface {
Write(string) error
}
type MyCloser interface {
Close() error
}
type fileWriter struct {
filepath string
}
type databaseWriter struct {
host string
port string
}
type writeCloser struct {
MyWriter
}
func (fw *fileWriter) Write(string) error {
fmt.Println("write string to error")
return nil
}
func (dw *databaseWriter) Write(string) error {
fmt.Println("write string to database")
return nil
}
func (wc *writeCloser) Close() error {
fmt.Println("close")
return nil
}
func main() {
var mw MyWriter = &writeCloser{
&databaseWriter{},
}
mw.Write("harry")
}
断言
package main
import (
"fmt"
"strings"
)
func add(a, b interface{}) interface{} {
switch a.(type) {`package main
import "fmt"
type MyInterWriter interface {
Write(string)
}
type MyInterReader interface {
Read() string
}
type MyReadWriter interface {
MyInterReader
MyInterWriter
ReadWrite()
}
type SreadWriter struct {
}
func (s *SreadWriter) Read() string {
fmt.Println("Read")
return ""
}
func (s *SreadWriter) Write(s2 string) {
fmt.Println("Write")
}
func (s *SreadWriter) ReadWrite() {
fmt.Println("ReadWrite")
}
func main() {
var mrw MyReadWriter = &SreadWriter{}
mrw.Read()
}
`
case int:
ai, _ := a.(int)
bi, _ := b.(int)
return ai + bi
case float64:
af, _ := a.(float64)
bf, _ := b.(float64)
return af + bf
case string:
as, _ := a.(string)
bs, _ := b.(string)
return as + bs
default:
panic("not supported type")
}
}
func main() {
re := add("hello", "world")
res, _ := re.(string)
strings.Split(res, " ")
fmt.Println(re)
}
嵌套接口
文章来源地址https://www.toymoban.com/news/detail-614335.html
文章来源:https://www.toymoban.com/news/detail-614335.html
到了这里,关于慕课网Go-3.函数、defer、panic、recover、结构体、指针、interface的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!