当前位置:网站首页>Understand the usage of functions and methods in go language
Understand the usage of functions and methods in go language
2022-07-05 17:13:00 【1024 questions】
Function definition syntax
Function definition example
No return function
Single return function
Multiple return function
Method (Method) Definition
Method (Method) Example
Basic types
Type of structure
Function definition syntaxConsistent with most languages ,Go The function definition in language is basically consistent with that in other languages
func function_name(Parameter-list) { // function body...}func function_name(Parameter-list) Return-Type { // function body...}func function_name(Parameter-list) (Multiple Return-Types){ // function body..}
func: Function definition keywords
function_name: The name of the function ,Go Language is mainly used camel-case( hump ) Way of naming , Also according to the nature of the function , Use initial case to distinguish functions , The details will be explained in the later special chapters Go The norms of language
Parameter-list: parameter list , If nothing can be ignored
Return-Type/Multiple Return-Types: Type of return value , namely return Type of return value , Here, three forms are distinguished :
No return value / Single return value / Multiple return values
The other two are slightly different in the use of parentheses , Single return types generally do not add parentheses , For multiple return values, you need to add parentheses
In addition, for the sake of beauty , Parentheses after the parameter list , There is a space between the suggestion and the return type
Function definition example No return functionfunc HelloFunc() { fmt.Println("Hello, World")}
Single return function This example demonstrates the parameter definition method and the return value type definition method
func HelloFunc(msg string) string { return "Hello, " + msg}
Multiple return function The type of the second return value is usually used to return an error , This is convenient for the program to handle exceptions
func HelloFunc(msg string) (string, error) { return "Hello, " + msg, nil}
Let's take a look at the complete code implementation , Call in main function HelloFunc when , You also need two variables to receive the corresponding values
package mainimport "fmt"func HelloFunc(msg string) (string, error) { return "Hello, " + msg, nil}func main() { printString, err := HelloFunc("World") if err == nil { fmt.Println(printString) }}
Method (Method) Definition Go There are no classes in language , So in Go Language provides a method definition similar to function definition , By adding Reciever type , Implement the definition of a method in a similar class , Methods can be used Reciver Properties of . Let's take a look at grammar :
func (Reciever-Name Type) function_name(Parameter-list) (Multiple Return-Types){ // function body..}
Because most definitions are the same as the above function definitions , No more details here , Just introduce the new part :
Reciever-Name: The type must be a custom type , Cannot be built-in int, string etc. , Use the words , Errors will be reported at compile time
Method (Method) Example Basic typesLet's look at a method implemented by basic types , Here we use a knowledge point that we haven't learned —— Custom type type, It will be explained in detail later , Don't tangle here . The meaning of this sentence is through custom types mystring Redefined variables , Essentially with string The same type .
type mystring string
Notice our function definition here , Before the function name , More (msg mystring) The definition of , And inside the function , We can also use msg
func (msg mystring) HelloFunc() { str := "Hello, " + msg fmt.Println(str)}
And in the main When calling in a function , Different from the function call above , We use call directly mymsg Methods HelloFunc, It implements a method similar to the above example
var mymsg mystringmymsg = "World"mymsg.HelloFunc()
The full code is shown below
package mainimport "fmt"type mystring stringfunc (msg mystring) HelloFunc() { str := "Hello, " + msg fmt.Println(str)}func main() { var mymsg mystring mymsg = "World" mymsg.HelloFunc()}
Type of structure In fact, from the source code of each project , Methods are more related to structures (struct) And interface (interface) Use it together , These will be explained in detail later , All you need to know is . Here is a simple example , Let's calculate the area of the rectangle .
Defines a structure rect, It contains two attributes: length and width
How to calculate the area area(),Reciver Defined as structure type , In this way, the body , You can use length and width to calculate the area
Main function , Defines a structure , And the initialization length and width are 3 and 4
Call the r.area() Complete the area calculation
package mainimport "fmt"type rect struct { width float64 height float64}func (r rect) area() float64 { return r.width * r.height}func main() { r := rect{3, 4} rectArea := r.area() fmt.Printf("Rect area is %v\n", rectArea)}
This article is about one article Go This is the end of the article on the usage of functions and methods in language , More about Go Language function Please search the previous articles of SDN or continue to browse the related articles below. I hope you will support SDN more in the future !
边栏推荐
- [wechat applet] read the life cycle and route jump of the applet
- Learnopongl notes (II) - Lighting
- C#(Winform) 当前线程不在单线程单元中,因此无法实例化 ActiveX 控件
- 【剑指 Offer】61. 扑克牌中的顺子
- 7.Scala类
- 调查显示传统数据安全工具面对勒索软件攻击的失败率高达 60%
- Learnopongl notes (I)
- PHP人才招聘系统开发 源代码 招聘网站源码二次开发
- [Jianzhi offer] 66 Build product array
- 飞桨EasyDL实操范例:工业零件划痕自动识别
猜你喜欢
随机推荐
Judge whether a string is a full letter sentence
采用药丸屏的iPhone14或引发中国消费者的热烈抢购
Embedded UC (UNIX System Advanced Programming) -1
Is it safe to open a securities account by mobile phone? Detailed steps of how to buy stocks
The third lesson of EasyX learning
張平安:加快雲上數字創新,共建產業智慧生態
IDC报告:腾讯云数据库稳居关系型数据库市场TOP 2!
URP下Alpha从Gamma空间到Linner空间转换(二)——多Alpha贴图叠加
CMake教程Step6(添加自定义命令和生成文件)
CMake教程Step1(基本起点)
Thoughtworks 全球CTO:按需求构建架构,过度工程只会“劳民伤财”
Wechat official account web page authorization login is so simple
Writing method of twig array merging
机器学习01:绪论
CMake教程Step5(添加系统自检)
Use byte stream to read Chinese from file to console display
WR | 西湖大学鞠峰组揭示微塑料污染对人工湿地菌群与脱氮功能的影响
7.Scala类
CMake教程Step3(添加库的使用要求)
Deep learning plus