First of all want to learn the language enthusiasts have other language programming experience, at least if it is completely zero base small white users, this tutorial may not be suitable for reading or try reading see, series of notes’s goal is to stand in the Angle of the other languages to learn a new language, understand the language, and then write a real Go programs.
The concept of variables and constants is common in programming languages, and it is the same for learning new languages. Variables refer to the special features of different programming languages, while constants are the common features of programming languages.
To learn the language as much as possible, standing on the macroscopic Angle analysis variables, and constants may laugh it off or programming languages is not rich, the so-called constant is also variable, anyway now let’s begin to Go language learning, this tutorial involves the source code is hosted in lot, if you need access to the source code, please visit directly Github.com/snowdreams1…
Write the first oneHello World
The program
The first thing you need to do to learn a programming language is write Hello World. Now let’s develop the first executable command-line program in Go.
Environment preparation can refer to the Goland editor
Create a new main directory and create a hello_world.go file with Simple Application as the file type. The editor will help you create the go skeleton.
The syntax prompt for selecting FMT.Println is triggered by typing FMT, and the FMT package is automatically imported.
The complete content is as follows for your reference only:
package main
import "fmt"
func main(a) {
fmt.Println("Hello World")}Copy the code
Click the green start button on the left, you can run the program directly or use the Terminal Terminal TAB of the program, and of course, you can also run the program using external command line tools.
The go run command runs directly, while the go build command produces an executable, and both output Hello World as desired.
Knowledge point induction
The Go application entry has the following requirements:
- It must be
main
Package:package main
- It must be
main
Methods:func main()
- Arbitrary file name does not have to be
main.go
The directory name is arbitrarymain
Directory.
The above rules can be easily verified in the editor. If any rule does not meet the rules, the program will report an error. This is why we use the editor instead of the command line to learn, which can help us find errors in time and verify the guess at any time.
To summarize, the main package doesn’t have to be in the main directory. The main method can be in any file.
This also means that the program entry in the directory does not necessarily is called the main directory, however, must be declared as the main package, although don’t understand why so design, this point and Java completely different, at least at least means Go file can be directly migration directory without the need for the reconstruction of the language level, may be a bit, but also a bit confused? !
The main function is notable for its differences:
main
The function does not support a return value, but can passos.Exit
Return to exit status
Func main (func main must have no arguments and no return values
The main function returns the Exit status code with the help of os.exit (-1), which can be identified by the status code.
main
The function does not support passing in arguments, but can passos.Args
To obtain parameters
On the Terminal TAB, run the go run hello_world. Go Snowdreams1006 command os.Args to output the command path and parameter values.
Practice basic grammar in test cases as you learn
The master has failed more times than the beginner has tried
Computer programming is not a science but an engineering subject, so you can better master knowledge and skills through hands-on practice. Fortunately,Go provides a built-in testing framework without loading third-party class library extensions, which is very conducive to learning and practicing.
Just touch Go language, there is no need to in-depth explain how to write standard test program, after all, the basic syntax has not started formal practice!
But the simple rules are still there, and in general, there are only two rules:
- Test file name with
_test
The end:XXX_test.go
Command custom and different, Java file name is generally the big camel name, the corresponding test file is XXXTest
- The test method name is
Test
At the beginning:TestXXX
The naming conventions are different from those of other programming languages. In Java, test methods are usually named in small camel’s name, and the corresponding test method is testXXX
- Test methods have fixed parameters:
t *testing.T
Java.lang.Exception: Method testXXX should have no parameters
Create a new Go File of type Empty and name it hello_world_test. The editor creates an Empty test File.
Write test method signature at this time, use editor automatic prompt function input t.log casually output some content, so complete the first test file.
Like the main program, the test method is also executable, and a green start button appears on the left side of the editor window. Run the test case and print PASS in the console window below the editor to verify that the test logic is correct!
Sample test file source code:
package main
import "testing"
func TestHelloWorld(t *testing.T){
t.Log("Hello Test")}Copy the code
Now that you’ve learned two basic ways, one is to write programs in the main method and the other is to write programs in the test method.
Both methods can test and verify our learning results at any time. If written in the main method, knowledge generally needs to be packaged into a separate method, and then run the method in the main method.
If written in the test method, you can run the test method separately rather than running it all at once in the main method.
Of course, you can go either way, but I prefer the test case approach.
implementationFibonacci
The sequence
Like 1,1,2,3,5,8,13,… The Fibonacci sequence starts with three elements, and the value of the next element is the sum of the values of the first two elements.
Remember learning junior high school history, about zhaojun plug story is widely known, Wang Zhaojun’s beauty is not the focus of this discussion, but the focus is to put zhaojun’s tragic life.
Han dynasty and Xiongnu and relatives in exchange for border peace, the Emperor of the Han Dynasty did not want his daughter to marry far north, so from the harem selected an ordinary maid-in-waiting to act as and relatives object, who thought that this maid-in-waiting had grown so beautiful,” a duck to the wild goose closed with a full moon “, can be rated as one of the four beauties of ancient China!
Zhaojun is shoulding and close important task, from now on began to be far away from home miserable life, along the way, yellow sand fly in the sky, hot and dry sadness, affection, Zhaojun took out along with the lute, playing a moving tears of << lute complain >>!
“Thousands of years of pipa for hu, clear resentment song in the theory “, may be too sad, even the wild geese in the sky have forgotten to fly, so harvest the beauty of geese!
Lao Shan has a beautiful concubine in this fat bona. You should wake up in your dreams. Unfortunately, your life will not be long.
Come so, zhaojun however full of joy, alien husband died, the mission was completed, should be able to return toward the big Han Dynasty native land of dream?
Destiny gets a person, xiongnu culture, the father dies son, fat wave has passed away, but still have small fat wave, put in han Dynasty ethic compendium often look, can’t be called inbred marriage is incest simply good!
Small fat wave + zhaojun = small fat wave, as long as zhaojun not dead, and zhaojun’s current husband unfortunately died first, then small fat wave will continue to take concubine baby, in theory is really endless sun sun also!
Fat Boona’s concubine story might look something like this:
Po Po, Zhaojun, Po Po
Zhaojun’s first husband: fat wave + Zhaojun = small fat wave, right now Zhaojun just gave birth to a baby
Po Po, Po Po, Zhaojun, Po Po Po
Zhaojun’s second husband: small fat wave + Zhaojun = small fat wave, zhaojun’s baby married his mother? No wonder Zhaojun suffering miserable, suffering, fortunately, this zhaojun did not have a baby, two girls!
Po Po, Po Po, Po Po, Zhaojun
The 3rd husband of zhaojun, small fat wave + zhaojun = small small fat wave, elder brother end younger brother and, still incest good, this generation I am calculate not come out.
Fatty bona concubine series, theoretically and yugong yizhan some fight, life is endless, inheriting his father’s business or brother and brother, the number is more and more, belly is bigger and bigger.
The above story, pure fiction, zhaojun out is a great thing, in exchange for a hundred years of peace, worthy of respect.
Let’s implement the Fibonacci sequence in Go.
func TestFib(t *testing.T) {
var a = 1
var b = 1
fmt.Print(a)
for i := 0; i < 6; i++ {
fmt.Print("", b)
temp := a
a = b
b = temp + b
}
fmt.Println()
}
Copy the code
The above simple example shows the basic use of variables, which can be summarized as follows:
- Variable declaration keyword
var
, the type name comes first and the variable type comes after, where the variable type can be omitted.
// Declare variables A and b
var a = 1
var b = 1
Copy the code
The above variable syntax looks like Js assignment at first glance, but strictly speaking it isn’t. The above variable assignment form is just a simplification of the following
// declare variable A with type int, and declare variable b with type int
var a int = 1
var b int = 1
Copy the code
The first version omits int, and the assignment of 1 automatically concludes to int, simplifying writing somewhat, although this form can be simplified further.
// omit the same var, add a pair of parentheses (), and place the variable inside the parentheses
var (
a = 1
b = 1
)
Copy the code
I might ask, can we simplify this a little bit more, because other languages don’t simplify like that, and the answer is yes!
// Continuously declare variables and assign values
var a, b = 1.1
Copy the code
Of course, there are other languages that do this too, and it’s not something to be proud of, but the following is a simplified version of Go.
Var = =; var = =
a, b := 1.1
Copy the code
I asked you to accept? A small variable assignment can play five patterns, awesome, my Go!
- Variable types can be omitted and type inference is done automatically by the compiler
Similar to Js writing habits, but is still strongly typed in nature, there is no automatic conversion of different types, will also say like Js variables?
- The same variable statement can assign values to different variables simultaneously
Taking Fibonacci number as an example, the example on Go’s official website uses the feature of simultaneous variable assignment. The complete code is as follows:
package main
import "fmt"
// fib returns a function that returns
// successive Fibonacci numbers.
func fib(a) func(a) int {
a, b := 0.1
return func(a) int {
a, b = b, a+b
return a
}
}
func main(a) {
f := fib()
// Function calls are evaluated left-to-right.
fmt.Println(f(), f(), f(), f(), f())
}
Copy the code
If you don’t have a clear understanding of this feature, it’s probably not a big deal.
In fact, as the saying goes, no contrast, no harm. Take a simple example: swap variables
func TestExchange(t *testing.T) {
a, b := 1.2
t.Log(a,b)
a, b = b, a
t.Log(a,b)
temp := a
a = b
b = temp
t.Log(a,b)
}
Copy the code
In other languages, if two variables need to be exchanged, the third temporary variable is generally introduced. However, the variable exchange realized by Go is very simple and clear, which also conforms to the thinking of human beings rather than computers.
It’s not clear if the underlying exchange will still be temporary, but it’s certainly handy!
Assigning to multiple variables at the same time is a syntax unique to Go, and other languages can declare multiple variables at the same time but not simultaneously assign.
- Constants are also interesting and have keyword declarations
const
.
Some programming languages do not enforce constants and variables. Constants can be logically treated as variables that cannot be modified, and are usually prompted by all uppercase letters to indicate that they are constants. To prevent constants from being modified, some programming languages may have additional keyword constraints.
Fortunately,Go’s constants provide the keyword const constraint and prohibit repeated assignments, which is nice and easy.
func TestConst(t *testing.T) {
const pi = 3.14
t.Log(pi)
// cannot assign to pi
pi = 2.828
t.Log(pi)
}
Copy the code
In addition to the language-level const constant keyword,Go also has a special keyword iota, which is often used with constants!
Iota can help you quickly set up constant values that are continuous or regular.
func TestConstForIota(t *testing.T) {
const (
Mon = 1 + iota
Tue
Wed
Thu
Fri
Sat
Sun
)
// 1 2 3 4 5 6 7
t.Log(Mon, Tue, Wed, Thu, Fri, Sat, Sun)
}
Copy the code
In most programming languages, the number represented by Monday is almost 0, and Tuesday is 1, and so on, leading to deviation from traditional understanding. In order to calibrate the deviation and more in line with Chinese habits, the number represented by Monday is 0 plus 1, and so on. After setting the initial IOTA, the law can be applied in the remaining weeks, in sequence 1,2,3,4,5,6,7
If you do not use IOTA, you may need to manually perform continuous assignment, which is tedious. The introduction of IOTA can not only help fast setting, but also carry out bit-level operations.
func TestConstForIota(t *testing.T) {
const (
Readable = 1 << iota
Writing
Executable
)
// 0001 0010 0100 is 1, 2, 4
t.Log(Readable, Writing, Executable)
}
Copy the code
The first bit is 1, indicating that the file is readable. The second bit is 1, indicating that the file is writable. The third bit is 1, indicating that the file is executable.
The readable, writable, and executable status of a file represents the permission status code of a file, thus realizing the basic permission operation of a file. Common permission codes are 755 and 644.
Bitwise & operation has nothing to do with programming language. “When two digits are 1 at the same time, the bitwise and result is 1, otherwise, the result is 0”. Therefore, given permission code, we can easily judge whether the permission has readable, writable, executable and other permissions.
// 0111 is 7, which means readable, writable, and executable
accessCode := 7
t.Log(accessCode&Readable == Readable, accessCode&Writing == Writing, accessCode&Executable == Executable)
// 0110 is 6, indicating unreadable, writable, and executable
accessCode = 6
t.Log(accessCode&Readable == Readable, accessCode&Writing == Writing, accessCode&Executable == Executable)
// 0100 is 4, indicating that it is unreadable, unwritable, and executable
accessCode = 4
t.Log(accessCode&Readable == Readable, accessCode&Writing == Writing, accessCode&Executable == Executable)
// 0000 is 0, indicating unreadable, unwritable, and unexecutable
accessCode = 0
t.Log(accessCode&Readable == Readable, accessCode&Writing == Writing, accessCode&Executable == Executable)
Copy the code
The binary representation of the readable is 0001. Therefore, as long as the binary representation of the target is 1, the result of the bitwise sum must be 0001 and 0001 It also happens to be a Readable permission code, so accessCode&Readable == Readable means that the target permission code is Readable.
If the target access codes of binary first instead of 1 0, 0 and 1 = 0, (0 | 1) ^ 0 = 0, so the bitwise and operation result certainly are all 0 or 0000, 0000 = = 0001 compare value false, also is the access code unreadable.
For example,accessCode&Writing == Writing result true means writable, otherwise not writable,accessCode&Executable == Executable result true means Executable,false Means not executable.
Having familiarized ourselves with ioTA’s mathematics and bit calculations, we struck while the iron was hot and continued to practice in file size units!
func TestConstForIota(t *testing.T) {
const (
B = 1< < (10 * iota)
Kb
Mb
Gb
Tb
Pb
)
// 1 1024 1048576 1073741824 1099511627776 1125899906842624
t.Log(B, Kb, Mb, Gb, Tb, Pb)
// 62.9 KB (64,411 bytes)
size := 64411.0
t.Log(size, size/Kb)
}
Copy the code
The base unit between Byte and Kilobyte is 1024, that is, 2^10, which can be expressed by ioTA moving 10 bits to the left.
Well, isn’t IOTA amazing? At the same time, are you a little confused like me? What is iota?
This product means “trace “, similar to the English word” little “, a little also means “a little “.
But ioTA seems to have the ability to increase beyond just a little, which is not what a quantifier like little can convey.
Therefore, it is possible that IOTA is not the original English meaning, perhaps the Greek alphabet language, the standard 24 Greek alphabet and the corresponding English annotations.
A capital | lowercase | English pronunciation | International phonetic alphabet | meaning |
---|---|---|---|---|
Α | Alpha. | alpha | / / ˈ æ lf goes | Angle, coefficient, angular acceleration |
Β | Beta. | beta | / ‘beit goes / | Flux coefficient, Angle, coefficient |
Γ | gamma | gamma | / ‘g æ m goes / | Conductivity coefficient, Angle, specific heat capacity ratio |
Δ | Delta t. | delta | / ‘delt goes / | Change, diopter, one to the second power |
Ε | Epsilon. | epsilon | /ep’silon/ | The cardinal number of logarithms, permittivity |
Ζ | zeta | zeta | Zi: t goes / / ‘ | Coefficient, azimuth, impedance, relative viscosity |
Η | eta | eta | / ‘I: t goes / | Hysteresis coefficient, efficiency |
Θ | Theta. | theta | Theta: I/’ t goes / | Temperature, Angle |
Ι | ι ℩ | iota | /ai’oute/ | Tiny, tiny |
Κ | κ | kappa | / ‘æ k p goes / | Dielectric constant, adiabatic exponent |
Sunday afternoon | Lambda. | lambda | / ‘l æ goes/md | Wavelength, volume, thermal conductivity |
Μ | mu | mu | /mju:/ | Coefficient of permeability, number of fretting friction systems, hydrodynamic viscosity |
Ν | argument | nu | /nju:/ | Magnetic resistance coefficient, fluid kinematic viscosity, photon frequency |
Ξ | Is deduced | xi | /ksi/ | Random number, an unknown specific value within a (small) interval |
Ο | &western | omicron | / oumaik ‘goes n/r | Higher order infinitesimal function |
∏ | PI. | pi | /pai/ | PI,π(n) denotes the number of prime numbers not greater than n |
Ρ | rho | rho | /rou/ | Electrical resistivity, polar diameter in cylindrical and polar coordinates, density |
∑ | Sigma ς | sigma | / ‘sigm goes / | Summation, surface density, transconductance, normal stress |
Τ | tau | tau | /tau/ | Time constant, shear stress |
Υ | nu | upsilon | / ju: p ‘sil goes n / | The displacement |
Φ | phi | phi | /fai/ | Flux, Angle, lens focus, heat flow |
Χ | χ | chi | /kai/ | Chi-square (χ2) distribution was found in statistics |
Ψ | Bits of | psi | /psai/ | Angular velocity, dielectric flux |
Ω | Omega. | omega | / ‘oumig goes / | Ohms, angular velocity, the electric Angle of the alternating current |
The Greek letter is often used in physics, chemistry, biology, science and other disciplines as a constant or variable, unlike the general English variable or constant, the Greek letter represents the variable or constant generally has a specific meaning!
So ioTA is the English word for the Greek letter I, and that variable or constant means tiny, a little bit.
Translated into natural language, this symbol means a little bit, if it means changed, it means a little bit more, if it means unchanged, it means just a little bit, that’s all.
Hold down the Ctrl key and hover the mouse over ioTA to enter the source code section as follows:
// iota is a predeclared identifier representing the untyped integer ordinal
// number of the current const specification in a (usually parenthesized)
// const declaration. It is zero-indexed.
const iota = 0 // Untyped int.
Copy the code
Brief translation:
Iota is a predefined identifier that represents the ordinal number of an unsigned integer in the current constant, indexed by 0.
The comments above seem obscure, but if they are constants, they should be treated as constants, ok? Why does a constant definition smell like a circular variable index?
To verify the conjecture, the ioTA values at each step are simulated using the simplest weekly conversion as an example.
const (
Iota = 0,Mon = 1 + 0 = 1, ioTA = 1, Mon = 1, Mon = 1
Mon = 1 + iota
Iota = 1,Tue = 1 + iota = 1 + iota = 2
Tue
Wed = 1 + Wed = 1 + Wed = 2 + Wed = 1 + Wed = 2 + Wed = 3
Wed
Thu
Fri
Sat
Sun
)
// 1 2 3 4 5 6 7
t.Log(Mon, Tue, Wed, Thu, Fri, Sat, Sun)
Copy the code
In the above conjecture, ioTA is declared as a constant variable I in the loop, each time declared, I ++, so the loop assignment can be completed only by defining the initial conditions of the loop and the loop increment variable.
const (
Mon = 1 + iota
Tue
Wed
Thu
Fri
Sat
Sun
)
// 1 2 3 4 5 6 7
t.Log(Mon, Tue, Wed, Thu, Fri, Sat, Sun)
var days [7]int
for i := 0; i < len(days); i++ {
days[i] = 1 + i
}
// [1 2 3 4 5 6 7]
t.Log(days)
Copy the code
In this way, ioTA seems to be the I of the loop variable, where Mon = 1 + IOta is the initial body of the loop,Mon~Sun finite constant is the termination condition of the loop, and each constant is the next loop.
If one example is not enough to verify the conjecture, then another!
const (
Readable = 1 << iota
Writing
Executable
)
// 0001 0010 0100 is 1, 2, 4
t.Log(Readable, Writing, Executable)
var access [3]int
for i := 0; i < len(access); i++ {
access[i] = 1 << uint(i)
}
/ / [1, 2 4]
t.Log(access)
Copy the code
The above two examples have preliminarily verified that IOTA may have a certain correlation with cyclic variable I, which can be further approximated to conjecture.
const (
// iota=0 const=1+0=1 iota=0+1=1
first = 1 + iota
// iota=1 const=1+1=2 iota=1+1=2
second
// iota=2 const=2+2=4 iota=2+1=3
third = 2 + iota
// iota=3 const=2+3=5 iota=3+1=4
forth
// iota=4 const=2*4=8 iota=4+1=5
fifth = 2 * iota
// iota=5 const=2*5=10 iota=5+1=6
sixth
// iota=6 const=6 iota=6+1=7
seventh = iota
)
// 1 2 4 5 8 6
t.Log(first, second, third, forth, fifth, sixth, seventh)
const currentIota = iota
/ / 0
t.Log(currentIota)
var rank [7]int
for i := 0; i < len(rank); i++ {
if i < 2 {
rank[i] = 1 + i
} else if i < 4 {
rank[i] = 2 + i
} else if i < 6 {
rank[i] = 2 * i
} else {
rank[i] = i
}
}
// [1 2 3 4 5 6 7]
t.Log(rank)
Copy the code
Iota is the index of cyclic variables in a set of constant initializations. When the set of variables is fully initialized, IOTA restarts the evaluation, so the new variable currentIota has a value of 0 instead of 7
Therefore, ioTA is often used as the initialization of a group of regular constants may be the reason behind the assignment of circular variables, according to this idea of understanding the previous ioTA examples are not any problem, as to whether this understanding is accurate, need to continue to learn Go for further verification, one of the words, for reference only!
A basic summary of variables and constants
- Variable with
var
Keyword declaration, constant useconst
Keyword declaration. - There are many forms of variable declaration and assignment, so it is best to use a unified form to avoid inconsistent styles.
- Variable types can be inferred automatically, but are still strongly typed in nature, with no automatic conversion between different types.
- A regular set of constants can be used
iota
Constant simplification can be temporarily understood as the assignment of a variable in a loop, which is converted into a constant initialization. - Variables and constants have similar initializations. Unlike other programming languages, multiple variables can be assigned in a single statement, simplifying code writing rules to some extent.
- Any variable or constant that is defined but not used is not allowed. Why declare it when you don’t need it? ! Prohibit redundant design, good or bad temporarily can not assess, since how to design, then abide by it!
Unusual variables and constants
The Fibonacci sequence is an infinitely increasing sequence of numbers like 1,1,2,3,5,8,13… The Fibonacci sequence is a sequence that starts with the third number and the next number is always the sum of the first two numbers.
If you start with the third number, then the first two numbers are the starting values of the Fibonacci sequence, and the rest of the Fibonacci sequence all follow the established rules. Take the first two numbers as variable A, and B progresses backwards in a loop to get a sequence of the specified length.
func TestFib(t *testing.T) {
var a int = 1
var b int = 1
fmt.Print(a)
for i := 0; i < 6; i++ {
fmt.Print("", b)
temp := a
a = b
b = temp + b
}
fmt.Println()
}
Copy the code
While the above solution is fairly straightforward, it’s not as neat as it should be, at least not using the features of Go. In fact, we could have done better, or used the Go language’s features, to achieve a clearer and simpler solution:
func TestFibSimplify(t *testing.T) {
a, b := 0.1
for i := 0; i < 6; i++ {
fmt.Print("", b)
a, b = b, a+b
}
fmt.Println()
}
Copy the code
And the first solution is different, this time move forward variable a, a, artificially create virtual node 0, variables of the next node b to the Fibonacci sequence of the first node 1, as the a and b have back on, the next cycle of node b directly within the rules, compared to the first solution to shorten a node.
A,b := 0, 1 is the initial value before the start of the cycle,b is the first node in the Fibonacci sequence, a, b = b, a+b semantics are very clear during the cycle, node A becomes node B, node B is the value of a+b.
Isn’t it amazing that neither temporary variable is used to store the value of variable A, nor variable overwrite occurs, and the exchange assignment operation of variable is directly completed?
It can be seen that a, b= b and a+b are not the sum of the execution results of a=b and b=a+b, but are completed at the same time. This is a bit magical. I wonder how Go realizes the simultaneous assignment of multiple variables.
If some friends know the secret, but also hope to give advice, we learn and progress together!
If this is a bit confusing, the next operation, which I’m sure you’ll be familiar with, is to swap the values of the two variables.
func TestExchange(t *testing.T) {
a, b := 1.2
t.Log(a, b)
a, b = b, a
t.Log(a, b)
temp := a
a = b
b = temp
t.Log(a, b)
}
Copy the code
Is the same, a, b = b, a multivariable assignment completed variable exchange directly at the same time, other programming language to achieve similar needs are generally adopt temporary variables stored in advance of a value in order to prevent the variable coverage, however the Go way unexpectedly and way of thinking, ordinary people have to say, this is really good!
Through simple the Fibonacci sequence, the introduction of the basic use of variables and constants, and Go source documents corresponding specification, introduction to hope to be able to show you the language, the basis of understanding and what’s the difference between other programming languages, and these differences to actual coding what is convenient to us, if can use familiar programming language implementation Go Language design ideas are also interesting.
Below, a brief summary of the main knowledge points involved in this paper, although variables and constants, but the focus is not on how to introduce the definition, but on the special and the corresponding practical application.
- There is no necessary connection between the directory where the source file resides and the package where the source file resides, i.e
package main
The source file is not necessarily presentmain
It doesn’t even have to be in the directorymain
Directory.
Go source files are in the hello directory, and hello_word.go is in the main directory, but the packages they are in are package Main
- Source file naming temporarily do not know what rules, but the test file naming must be
xxx_test
, the test method is namedTestXXX
, includingGo
Testing frameworks are naturally supported without the need to load additional third party libraries.
- The keyword for declaring a variable is
var
, the keyword for declaring constants isconst
There are several ways to declare both variables and constants, and automatic type inference can simplify things.
In general, other programming languages implement global variable declarations using var, local variable declarations := simplified form, where multiple variables can be assigned at the same time.
- A set of constant values for a particular pattern can be skillfully used
iota
To implement, can be understood as the first useiota
Is the first of a set of constants, and the rest of the constants are initialized accordingly.
The Go language has no enumeration classes, so enumerations can be implemented with a set of constant values. After all, enumerations are special constants.
The source of this article has been uploaded to github.com/snowdreams1… Interested partners can click to view the project, if there is any improper description in the article, please point out, thank you for your comments and forwarding.