当前位置:网站首页>In go language, function is a type

In go language, function is a type

2022-07-07 08:27:00 Code two brother

0  grpc-go、protobuf、multus-cni Technical column The main entrance

1  grpc-go Source code analysis and actual combat    List of articles

2  Protobuf Introduction and actual combat Graphic column    List of articles

3  multus-cni    List of articles (k8s Multi network implementation scheme )

4  grpc、oauth2、openssl、 Two-way authentication 、 One way authentication and other column contents

summary ( Remember the following three sentences )

1、 function , It is also a kind of type ( Pay special attention to )
2、 function , I can assign a value to Variable ( want special Be careful )
 Functions can be assigned to variables
 Create function variables
3、 function , It can be used as Parameters , To pass

package func5_test

import (
	"testing"
	"fmt"
)

// Make a statement fire function 
func fire()  {
	fmt.Print("--->this is fire func")
}

func study(str string)  {
	fmt.Printf("--->I'm studying %s", str)
}

//  test , Whether the function is assigned to a variable 
func TestFuncVariable(t *testing.T)  {
	//  Declare variables f, The type is func type , Function type 
	//  Put the variable  f  Declare as  func()  type ,
	//  call f When , It's actually calling theta fire function , here  f  It is commonly known as “ Callback function ”, 
       //  here  f  The value of is  nil
	var f func()

	f = fire

	f()
}

//  test , Whether the function is assigned to a variable 
func TestStudy(t *testing.T)  {

	st := study

	st("English")
}

//  test , Whether the function type can be passed as a parameter 
func learning(f func())  {
	fmt.Printf("--->this is running func")
	f()
}

func TestFuncParams(t *testing.T)  {
	f := fire
	//  Pass the function as an argument 
	learning(f)
}

原网站

版权声明
本文为[Code two brother]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207070525336247.html