当前位置:网站首页>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 stringNotice 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 !
边栏推荐
- Copy mode DMA
- Embedded UC (UNIX System Advanced Programming) -2
- 【jmeter】jmeter脚本高级写法:接口自动化脚本内全部为变量,参数(参数可jenkins配置),函数等实现完整业务流测试
- American chips are no longer proud, and Chinese chips have successfully won the first place in emerging fields
- 【beanshell】数据写入本地多种方法
- 麻烦问下,DMS中使用Redis语法是以云数据库Redis社区版的命令为参考的嘛
- ECU简介
- C# TCP如何限制单个客户端的访问流量
- Use JDBC technology and MySQL database management system to realize the function of course management, including adding, modifying, querying and deleting course information.
- npm安装
猜你喜欢
随机推荐
域名解析,反向域名解析nbtstat
飞桨EasyDL实操范例:工业零件划痕自动识别
微信公众号网页授权登录实现起来如此简单
Excuse me, is the redis syntax used in DMS based on the commands of the redis community version of the cloud database
[wechat applet] read the life cycle and route jump of the applet
激动人心!2022开放原子全球开源峰会报名火热开启!
菜刀,蚁剑,冰蝎,哥斯拉的流量特征
Etcd 构建高可用Etcd集群
Is it safe for qiniu business school to open a stock account? Is it reliable?
Practical example of propeller easydl: automatic scratch recognition of industrial parts
一文了解MySQL事务隔离级别
编译libssh2报错找不到openssl
How can C TCP set heartbeat packets to be elegant?
网上办理期货开户安全吗?网上会不会骗子比较多?感觉不太靠谱?
How does the outer disk futures platform distinguish formal security?
Machine learning compilation lesson 2: tensor program abstraction
一个满分的项目文档是如何书写的|得物技术
[Web attack and Defense] WAF detection technology map
Function sub file writing
What is ROM




![[Jianzhi offer] 63 Maximum profit of stock](/img/b6/c1dec97a23ac13aa53d1d202b83ef5.png)




