当前位置:网站首页>[go language question brushing chapter] go conclusion chapter | introduction to functions, structures, interfaces, and errors
[go language question brushing chapter] go conclusion chapter | introduction to functions, structures, interfaces, and errors
2022-07-04 18:24:00 【Study notes of Zhou】
Go from 0 To the beginning 6-Go Conclusion
- Preface
- Q1: function - Factorial of numbers
- Q2: function - The absolute value
- Q3: function - Add, subtract, multiply and divide
- Q4: Structure - Student information 1
- Q5: Structure - Student information 2
- Q6: Interface - Animals and tigers
- Q7: error - Network delay
- Q8: error - Abnormal body temperature
- later : Brush Title artifact
Preface
- This period is for learning Golang The end of : function 、 Structure 、 Interface 、 Error introductory learning , If you don't understand something, you can comment and discuss it !
- Next I will continue to update Python Brush questions series 、 Database from 0 To the entry brush question series and so on .
- This series of articles adopts the core code mode of Niuke to provide case code , Help you from 0 To the beginning of the learning process of supporting brush questions ~
- I recommend a brush question for you 、 Interview artifact , I also use this artifact to learn !~ Links are as follows : Brush question artifact jump link
- The artifact not only has a beautiful web interface , And the operation is very easy to get started ! It is very suitable for beginners to learn systematically !
- Novice Xiaobai can use this artifact to brush questions everyday 、 Look at the face of Dachang 、 Learn the basics of computer 、 Communicate with Daniel face to face ~ The picture of question brushing has been placed below ~
Q1: function - Factorial of numbers
Problem description : The factorial of a positive integer (factorial) Is the product of all positive integers less than or equal to the number , also 0 The factorial of is 1. Natural number n The factorial writing of n!.
Related knowledge :
1、 recursive , It is to call itself in the process of running . A function calls itself , It's called a recursive function . The conditions that constitute recursion : The sub problem must be the same thing as the original problem , And it's simpler . You can't call itself unlimited , There must be an exit , Reduction to non recursive state processing .
Instance input :2
Instance output :2
Case code :
//import "fmt"
/** * The class name in the code 、 Method name 、 The parameter name has been specified , Do not modify , Return the value specified by the method directly * @param i int integer Numbers * @return int integer */
func factorial( i int ) int {
// write code here
if i == 0{
return 1
}
return i * factorial(i-1)
}
Q2: function - The absolute value
Problem description : Define a function , The function of the function is to give a number , Returns the absolute value of the number .
Related knowledge :
1、 Definition of function : The function declaration contains a function name , parameter list , Return value list and function body . If the function does not return a value , The returned list can be omitted . The function starts with the first statement , Until the execution of return Statement or the last statement that executes a function . Functions can have no arguments or accept multiple arguments . Note that the type is after the variable name . When two or more consecutive function named arguments are of the same type , Except for the last type , Anything else can be omitted . Function can return any number of return values . Use keywords func Defined function , The left brace still cannot start another line .
func function_name( [parameter list] ) [return_types] {
The body of the function
}
2、 Function call : When creating a function , You define what the function needs to do , Perform the specified task by calling this function . Call function , Pass arguments to the function , And the return value
3、Go Function can return multiple values ,"_" identifier , Used to ignore a return value of a function Go The return value of can be named , And it's just like a function at the beginning of a variable . The name of the return value should have some meaning , Can be used as a document . Without parameters return Statement returns the current value of each return variable .
Instance input :-1
Instance output :1
Case code :
//import "fmt"
/** * The class name in the code 、 Method name 、 The parameter name has been specified , Do not modify , Return the value specified by the method directly * @param x int integer * @return int integer */
func absfunc(x int) int {
// write code here
if x < 0 {
return -x
}
return x
}
Q3: function - Add, subtract, multiply and divide
Problem description : Define a function , Implement input a,b Two Numbers , Returns the sum of two numbers , Bad , The product of , merchant , remainder . Then it is stored in slices in turn , Finally back to .
Related knowledge :
1、Go Functions in support of multiple return values , But when a function has multiple return values , If one or more of the return values do not want to be used , You can underline _ To discard these return values . For example, the following f1 The function returns two values , When the function is called , The second return value is discarded b, Only the first return value is retained a Assigned to a variable a.
Instance input :2,2
Instance output :[4,0,4,1,0]
Case code :
//import "fmt"
/** * The class name in the code 、 Method name 、 The parameter name has been specified , Do not modify , Return the value specified by the method directly * @param a int integer * @param b int integer * @return int Integer one-dimensional array */
func operate( a int , b int ) []int {
// write code here
var ans []int
ans = append(ans, a+b)
ans = append(ans, a-b)
ans = append(ans, a*b)
ans = append(ans, a/b)
ans = append(ans, a % b)
return ans
}
Q4: Structure - Student information 1
Problem description : Each student has the following information : full name name, Gender sex, Age age, fraction score, Define a structure Student, To express Xiao Ming's information , Xiao Ming's information is as follows : full name : Xiao Ming , Gender :true, Age :23, fraction :88
Related knowledge :
1、Go The basic data types in language can represent the basic properties of some things , But when we want to express all or part of the attributes of a thing , At this time, a single basic data type is obviously unable to meet the demand ,Go The language provides a custom data type , It can encapsulate multiple basic data types , This type of data is called a structure , English name struct. That is, we can go through struct To define your own type .
2、 A structure consists of a series of named elements , These elements are also called fields , Each field has a name and a type .
3、 The purpose of a structure is to aggregate data , In order to be able to operate these data more easily .
4、 Definition of structure : Structure definition needs to use type and struct sentence .struct Statement to define a new data type , A structure has one or more members .type Statement sets the name of the structure . The format of the structure is as follows :
type Type name struct {
Field name Field type
Field name Field type
…
}
Type name : Identifies the name of the custom structure , Cannot repeat in the same package .
Field name : Represents the structure field name . Field names in structures must be unique .
Field type : Represents the specific type of structure field .
5、 Access members of the structure : If you want to access structure members , You need to use a dot . The operator .
Sample input : nothing
Sample output :
Xiao Ming
true
23
88
Case code :
import "fmt"
type stu struct {
name string
sex bool
age int
score int
}
func main() {
a := stu{
name: " Xiao Ming ",
age: 23,
sex: true,
score: 88,
}
fmt.Println(a.name)
fmt.Println(a.sex)
fmt.Println(a.age)
fmt.Println(a.score)
}
Q5: Structure - Student information 2
Problem description : Each student has the following information : full name name, Gender sex, Age age, fraction score, Address information address, among address The address information also includes the city city, Province province Etc , Define a structure Student, To express Xiao Ming's information , Xiao Ming's information is as follows : full name : Xiao Ming , Gender :true, Age :23, fraction :88,province: Hunan province ,city: Changsha City .
Output and print Xiaoming information in turn
Related knowledge :
1、 One structure can be nested with another structure or structure pointer .
Sample input :
Sample output :
Xiao Ming
true
23
88
Hunan province
Changsha City
Case code :
import (
"fmt"
)
type address struct {
city string
prov***ring
}
type stu struct {
name string
sex bool
age int
score int
add address
}
func main() {
a := stu{
name: " Xiao Ming ",
age: 23,
sex: true,
score: 88,
add: address{
city: " Changsha City ",
province: " Hunan province ",
},
}
fmt.Println(a.name)
fmt.Println(a.sex)
fmt.Println(a.age)
fmt.Println(a.score)
fmt.Println(a.add.province)
fmt.Println(a.add.city)
}
Q6: Interface - Animals and tigers
Problem description : Define an animal interface , This interface has sleep,eat Method , Define the tiger to implement the animal interface , Tiger sleep Method output "tiger sleep",eat Method output "tiger eat", Finally, call tiger's sleep,eat Method .
Related knowledge :
1、 stay Go Interface in language (interface) It's a type of , An abstract type .interface It's a group. method Set , yes duck-type programming A manifestation of . Interfaces do things like defining a protocol ( The rules ), As long as a machine has the function of washing and drying , I call it a washing machine . Don't care about attributes ( data ), Only care about behavior ( Method ).
2、 Interface (interface) Defines the behavior of an object , Only define the specification, not implement , Specification details are implemented by specific objects . Interface oriented programming
3、 An interface is a collection of one or more method signatures .
4、 Any type of method set as long as it has the interface ’ All corresponding methods ’ Signature . It means it's “ Realization ” The interface , There is no need to explicitly declare which interface is implemented on the type . This is called Structural Typing. The so-called correspondence method , Means having the same name 、 parameter list ( Parameter names are not included ) And the return value . Of course , This type can also have other methods .
5、 Interface has only method declarations , It didn't come true , No data fields . Interfaces can be embedded anonymously into other interfaces , Or embedded in the structure .
6、type Interface type name interface{
Method name 1( parameter list 1 ) Return value list 1
Method name 2( parameter list 2 ) Return value list 2
…
}
Sample input : nothing
Sample output :
sleep
eat
Case code :
import "fmt"
type animal interface {
sleep()
eat()
}
type tiger struct {
}
func (t tiger) sleep() {
fmt.Println("sleep")
}
func (t tiger) eat() {
fmt.Println("eat")
}
func main() {
var t animal = tiger{
}
t.sleep()
t.eat()
}
Q7: error - Network delay
Problem description : Realization erro Interface , Customize an error , This error is thrown " Network delay " error . Enter the delay number of the network , If the delay is greater than 100 Network delay , And back to
Related knowledge :
1、 error :Go The language provides a very simple error handling mechanism through a built-in error interface .
type error interface {
Error() string
}
2、 Realization error Interface type to generate error messages , Function usually returns error information in the last return value . Use errors.New Can return an error message
Sample input :150
Sample output :“ Network delay ”
Case code :
import "errors"
type error interface {
Error() string
}
func Error() string {
return " Network delay "
}
func defineerr(ping int) string {
// write code here
if ping > 100 {
errors.New(" Network delay ")
return " Network delay "
}
return ""
}
Q8: error - Abnormal body temperature
Problem description : Implement a function , The function of this function is Given a float The type variable represents a person's body temperature , If someone's temperature is greater than 37.5, Throw out " Abnormal body temperature ", And the output .
Related knowledge :
1、Go You can throw a panic It's abnormal , And then in defer Pass through recover Catch this exception , And then deal with it normally .
Sample input :38.000000
Sample output :“ Abnormal body temperature ”
Case code :
//import "fmt"
/** * The class name in the code 、 Method name 、 The parameter name has been specified , Do not modify , Return the value specified by the method directly * @param t double floating-point Temperature * @return string character string */
func temperature(t float64) (ans string) {
// write code here
ans = ""
defer func() {
err := recover()
if err != nil {
ans = " Abnormal body temperature "
}
}()
if t > 37.5 {
panic(" Abnormal body temperature Pop up warning !")
}
return ans
}
later : Brush Title artifact
Click the link to jump to registration , Start your nanny level question brushing ! Brush the questions and write strange codes. The way of God
In addition, we can not only brush questions here , There will be everything you want , It is very suitable for Xiaobai and beginners ~
1、 Algorithm (398 topic ): Interview must brush 100 topic 、 Introduction to algorithm 、 Interview frequency list
2、 Data structure (300 topic ): Are very classic linked lists 、 Trees 、 Pile up 、 Stack 、 queue 、 Dynamic planning, etc
3、 Language (500 topic ):C/C++、java、python Introductory algorithm exercises
4、SQL piece (82 topic ): Quick start 、SQL Will know 、SQL Advanced challenges 、 The real question of the interview
5、 The real question of the written test of Dachang : Bytes to beat 、 Meituan 、 Baidu 、 tencent … Master the experience and don't be afraid of the interview !
边栏推荐
- 【每日一题】871. 最低加油次数
- I wrote a learning and practice tutorial for beginners!
- DB engines database ranking in July 2022: Microsoft SQL Server rose sharply, Oracle fell sharply
- 【系统盘转回U盘】记录系统盘转回U盘的操作
- Is it science or metaphysics to rename a listed company?
- Open source PostgreSQL extension age for graph database was announced as the top-level project of Apache Software Foundation
- 爬虫初级学习
- 明星开店,退,退,退
- SIGMOD’22 HiEngine论文解读
- Make a grenade with 3DMAX
猜你喜欢
力扣刷题日记/day7/6.30
[test development] software testing - Basics
Reptile elementary learning
Journal des problèmes de brosse à boutons de force / day6 / 6.28
Li Kou brush question diary /day6/6.28
明星开店,退,退,退
DB-Engines 2022年7月数据库排行榜:Microsoft SQL Server 大涨,Oracle 大跌
I wrote a learning and practice tutorial for beginners!
2022年全国CMMI认证补贴政策|昌旭咨询
Make a grenade with 3DMAX
随机推荐
Neglected problem: test environment configuration management
78 year old professor Huake impacts the IPO, and Fengnian capital is expected to reap dozens of times the return
Introduction of time related knowledge in kernel
Easy to use map visualization
celebrate! Kelan sundb and Zhongchuang software complete the compatibility adaptation of seven products
2022 national CMMI certification subsidy policy | Changxu consulting
【系统分析师之路】第七章 复盘系统设计(结构化开发方法)
用于图数据库的开源 PostgreSQL 扩展 AGE被宣布为 Apache 软件基金会顶级项目
2022年DCMM认证全国各地补贴政策汇总
The controversial line of energy replenishment: will fast charging lead to reunification?
华为云ModelArts的使用教程(附详细图解)
网上开户安全吗?是真的吗?
力扣刷题日记/day8/7.1
I wrote a learning and practice tutorial for beginners!
Russia arena data releases PostgreSQL based products
表情包坑惨职场人
【每日一题】871. 最低加油次数
俄罗斯 Arenadata 发布基于PostgreSQL的产品
Superscalar processor design yaoyongbin Chapter 7 register rename excerpt
Li Kou brush question diary /day5/2022.6.27