Interesting Variables and Disturbed Constants in Go Learning Notes

Time:2019-10-9

First of all, I hope to learn.GoLanguage enthusiasts have at least programming experience in other languages. If they are completely zero-based white users, this tutorial may not be suitable for reading or trying to read. The goal of this series of notes is to learn new languages from the perspective of other languages and understand them.GoLanguage, and then write the realGoProcedure.

Variables and constants are commonly concepts in programming languages. The same is true for learning new languages. Variables refer to the particularities of different programming languages, and constants are the common denominator of programming languages.

StudyGoLanguage as far as possible stand on the macro point of view to analyze variables, and constants may laugh over or programming language is not rich enough, so-called constants are actually variables, anyway, let’s start now.GoLanguage learning trip, the source code involved in this tutorial has been hosted ingithubFor source code, visit https://github.com/snowdreams 1006/learn-go directly

Write the firstHello Worldprogram

The first thing to learn programming languages is to write them.Hello WorldNow let’s use itGoLanguage to develop the first runnable command line program bar!

Preparations for the Environment Reference to Goland Editor

Newly buildmainDirectory, and newhello_world.goFile, where file type selectionSimple ApplicationThe editor will help us createGoProgram skeleton.

Input firstfmtPost-triggered grammatical prompt selectionfmt.PrintlnThen it will import automaticallyfmtPack.

The complete contents are as follows, for reference only:

package main

import "fmt"

func main() {
    fmt.Println("Hello World")
}

Click the green start button on the left to run the program directly or make use of the program’s ownTerminalThe terminal tab runs the program. Of course, it can also run the program with external command line tools.

go runThe command runs directly, andgo buildCommand generates executable files, which can be output in both ways as desiredHello World .

Knowledge Point Induction

GoThe following requirements are required for application entry:

  • Must bemainPack:package main
  • Must bemainMethod:func main()
  • File names are arbitrary and not necessarilymain.goThe directory name is arbitrary and not necessarilymainCatalog.

The above rules can be easily verified in the editor. If any rule does not conform to the rules, the program will report errors. This is the reason why we use the editor instead of the command line to learn. It can help us find errors in time and verify guesses at any time.

In conclusion,mainThe package is not necessarily inmainUnder the catalogue,mainMethod can be in any file.

This also means that the directory where the program entry is located is not necessarily calledmainCatalogues must be declared asmainThe package, though not understanding why it was designed, at least withJavaIt’s totally different, at least that meansGoDocuments can migrate directories directly without requiring linguistic restructuring. There may be some aspects, but also some doubts?!

mainNotable differences in functions:

  • mainFunctions do not support return values, but they canos.ExitReturn to exit status

mainFunction, does not support return values, if forced to run at this timemainMethod, error will be reported:func main must have no arguments and no return values

mainFunctions can be usedos.Exit(-1)Return the state code when the program exits, and the outside world can identify the corresponding state according to different state codes.

  • mainFunctions do not support incoming parameters, but they can be passed throughos.ArgsGetting parameters

stayTerminalRunning in Terminal Tabgo run hello_world.go snowdreams1006commandos.ArgsOutput command path and parameter values.

Practice basic grammar while learning in test cases

The master has failed more times than the beginner has tried

Computer programming is not science but engineering. Only by practicing it in person can we master knowledge and skills better. Fortunately,GoThe built-in language provides a testing framework without loading third-party class library extensions, which is very conducive to learning and practice.

Just contactedGoLanguage, do not need to explain how to write a standardized test program, after all, the basic grammar has not yet started formal practice!

However, the simple rules still need to be said. Generally speaking, there are only two rules:

  • Test file name with_testEnding:XXX_test.go

Command habits and differences,JavaFile names in theNomenclature of Great HumpThe corresponding test file isXXXTest

  • The test method name isTestStart:TestXXX

Naming habits are different from other programming languages.JavaThe test method naming in theNaming of HumpsThe corresponding test method istestXXX

  • Test methods have fixed parameters:t *testing.T

There are no parameters in other programming languages.JavaThere must be no parameters in the test method, otherwise an exception will be thrown.java.lang.Exception: Method testXXX should have no parameters

Newly buildGoFile, Type SelectionEmpty FileThe file name is namedhello_world_testThe editor creates a new blank test file.

Write test method signature at this time, and use the editor’s automatic prompt function to inputt.LogOutput some content at random, so that the first test file is completed.

andmainSimilar to the program, the test method is also executable. The green start button will appear on the left side of the editor window. Running test cases will be output from the console window below the editor.PASSProve that the test logic is correct!

Examples of test file source code:

package main

import "testing"

func TestHelloWorld(t *testing.T){
    t.Log("Hello Test")
}

Now we have learned two basic ways, one is to write programs inmainThe other method is to write the program in the test method.

Both methods can be tested at any time to verify our learning results, if written inmainIn the method, knowledge points are usually packaged into separate methods, and then in themainThe method is run in the method.

If written in the test method, you can run the test method separately instead of in the test method.mainThe method runs all at once.

Of course, both approaches are possible, except that individuals tend to test case approaches.

RealizationFibonacciseries

Like1,1,2,3,5,8,13,...Formal sequence is Fibonacci sequence, which is characterized by starting from three elements. The value of the next element is the sum of the first two elements. There are endless descendants.

I remember learning the history of junior high school, the story about Zhaojun’s fortress is well known, Wang Zhaojun’s beauty is not the focus of this discussion, and the focus of this discussion is on Zhaojun’s tragic life.

The Han Dynasty and the Huns exchanged for peace along the border with their relatives. The emperor of the Han Dynasty did not want his relatives and daughters to marry far away from Saibei. So he chose an ordinary palace maid from the back palace as his relatives. Who imagined that the palace maid had such a beautiful appearance, “sunk fish, fallen wild goose, closed the moon and shy flowers”, which could be regarded as one of the four beautiful women in ancient China!

Zhaojun shouldered the heavy responsibility and personally began to live a miserable life far away from his hometown. Along the way, Huangsha was flying, hot and sad, and his feelings were at their best. Zhaojun took out his casual Pipa and played “Pipa Complaint” under moving tears.

“Thousands of years of Pipa as nonsense, clear resentment in the song,” may be too sad, even the geese in the sky have forgotten to fly, so harvest.a kind of medicinal plantBeauty!

Old only in this Feibona a concubine like flowers, can you wake up from dreams, unfortunately, life is not long!

In this way, Zhaojun was full of joy. His alien husband died and his mission was completed. Should he be able to return to the homeland of the Han Dynasty, where he dreamed of his dreams?

Destiny, Hun culture, father and son, fat wave has passed away, but there are still small fat wave ah, put in the Han Dynasty ethics outline, can not be called close relatives married simply incest is good!

Xiaofeibo + Zhaojun = XiaofeiboAs long as Zhaojun does not die, and Zhaojun’s current husband unfortunately dies first, Xiao Feibo will continue to take concubines and give birth to babies. In theory, it is really endless descendants!

The story of Concubine Fabona may grow like this:

  • Feibo, Zhaojun, Xiaofeibo

Zhaojun’s first husband:Feibo + Zhaojun = XiaofeiboAt this time, Zhaojun just gave birth to a baby

  • Feibo, Xiaofeibo, Zhaojun, Xiaofeibo

Zhaojun’s second husband:Xiaofeibo + Zhaojun = XiaofeiboZhaojun’s baby married his mother? No wonder Zhaojun was miserable and miserable. Fortunately, Zhaojun didn’t have a baby this time. Two girls!

  • Feibo, Xiaofeibo, Xiaofeibo, Zhaojun

Zhaojun’s third husband,Xiaofeibao + Zhaojun = XiaofeibaoBrothers and brothers, or incest, I can’t figure it out in this generation.

Feibona concubine series, in theory, is competing with Yu Gong’s move to the mountains. Life goes on and on. It’s better for the son to inherit his father’s career, for the brother and the brother, and for the last time. The number of concubines is increasing and the stomach is getting bigger and bigger.

The above story is pure fiction. Zhaojun’s leaving the fortress is a great thing. In exchange for a hundred years of peace, it is worthy of respect.

Back to the point, let’s useGoLanguage to achieve Fibonacci sequence bar!

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()
}

The above simple examples show the basic use of variables, which can be summarized as follows:

  • Variable declaration keywordvarThe type name is in the first place and the variable type is in the second place, in which the variable type can be omitted.
// Declare variables A and B
var a = 1
var b = 1

How does the above variable grammar look like?JsAssignment, strictly speaking, is not the case. The above variable assignment form is just the following simplification.

// Declare variable a and specify type int, similarly declare variable B and specify type int
var a int = 1
var b int = 1

The first way of writing is omitted.intType, by assignment1Automatic inferenceintTo a certain extent, it simplifies writing, of course, this form can continue to simplify.

// Eliminate the same var, add a pair of parentheses (), and put variables in parentheses. 
var (
    a = 1
    b = 1
)

May ask, can we continue to simplify, after all, the simplified form of other languages is not the same, the answer is yes!

// Continuous declaration of variables and assignment
var a, b = 1, 1

Of course, other languages have similar expressions, which is not to be proud of. Here is the form.GoA simplified version of language.

// The keyword VaR is omitted and the assignment symbol = is changed to: =, which means declaring variables and assigning values. 
a, b := 1, 1

Just ask you if you are convinced? A small variable assignment can play five tricks. Great, mine.Go !

  • Variable types can be omitted and automatically inferred by the compiler

SimilarJsWriting habits, but essentially still strong type, will not carry out different types of automatic conversion, will say likeJsIs it a variable?

  • The same variable statement can assign different variables at the same time.

Still withFibonacci sequenceFor example,GoThe example of official website uses the feature of simultaneous assignment of variables. The complete code is as follows:

package main

import "fmt"

// fib returns a function that returns
// successive Fibonacci numbers.
func fib() func() int {
    a, b := 0, 1
    return func() int {
        a, b = b, a+b
        return a
    }
}

func main() {
    f := fib()
    // Function calls are evaluated left-to-right.
    fmt.Println(f(), f(), f(), f(), f())
}

If you don’t have a clear understanding of this feature, you may think it’s not a big deal.

In fact, as the saying goes, there is no harm without comparison. Let’s take a simple example: swapping 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)
}

In other languages, if two variables need to be exchanged, the third temporary variable is usually introduced.GoThe realization of variable exchange is very simple and clear, which is also in line with human thinking rather than computer thinking.

Although it is not clear whether temporary variable exchange will still be used at the bottom, it is convenient to use this feature anyway.

Assigning multiple variables at the same time isGoA unique grammar, other languages can declare multiple variables at the same time, but can not assign values at the same time.

  • Constants are also interesting, with keyword declarationsconst.

In some programming languages, constants and variables are not mandatory. Constants can be logically regarded as variables that will not be modified. Generally, users are prompted with full capitals as constants. In order to prevent constants from being modified, some programming languages may have additional keywords to constrain them.

Fortunately,GoLanguage constants provide keywordsconstConstraints, and prohibition of repeated assignments, this is very good, simple and convenient.

func TestConst(t *testing.T) {
    const pi = 3.14
    t.Log(pi)

    // cannot assign to pi
    pi = 2.828
    t.Log(pi)
}

Except at the linguistic levelconstConstant keywords,GoLanguage also needs a special keywordiotaOften used with constants!

When some continuous constant values or regular constant values are set,iotaIt can help us set it up quickly.

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)
}

In most programming languages, the number of Monday delegates is almost all0Tuesday1By analogy, it leads to deviation from traditional understanding. In order to calibrate the deviation and conform to the habits of the Chinese people, the number of Representatives on Monday will be calculated.0Add one, and by analogy, set the initialiotaThen the rule can be applied in the remaining weeks, in turn.1,2,3,4,5,6,7

If not usediotaIf so, it may be necessary to assign continuously manually, which is rather cumbersome and introduced.iotaIn addition to helping with quick settings, it can also be doneBit bitLevel of operation.

func TestConstForIota(t *testing.T) {
    const (
        Readable = 1 << iota
        Writing
        Executable
    )
    // 0001 0010 0100 or 124
    t.Log(Readable, Writing, Executable)
}

The first bit is1When the file is readable, the second bit is1When it is written, the third bit is1When executable, corresponding10The numeric values are in turn1,2,4That is, to move one left, two left and three left, which can also be recorded mathematically.2^0,2^1,2^2 .

The readable, writable and executable three states of the file represent the permission status code of the file, thus realizing the basic permission Operation of the file. The common permission codes are as follows:755and644.

Location and&Operations have nothing to do with programming languages.1When the result is in place, the result is1Otherwise, the result is0Therefore, given the permission code, we can easily determine whether the permission has readable, writable, executable and other permissions.

// 0111, or 7, means readable, writable, and executable
accessCode := 7
t.Log(accessCode&Readable == Readable, accessCode&Writing == Writing, accessCode&Executable == Executable)

// 0110, or 6, means unreadable, writable, and executable
accessCode = 6
t.Log(accessCode&Readable == Readable, accessCode&Writing == Writing, accessCode&Executable == Executable)

// 0100, or 4, means unreadable, non-writable, and executable
accessCode = 4
t.Log(accessCode&Readable == Readable, accessCode&Writing == Writing, accessCode&Executable == Executable)

// 0000 is 0, which means that it is unreadable, unwritable and unenforceable.
accessCode = 0
t.Log(accessCode&Readable == Readable, accessCode&Writing == Writing, accessCode&Executable == Executable)

accessCode&ReadableRepresents the target permission code and the readable permission code for bit-by-bit operation, while the binary representation value of the readable permission code is0001So as long as the binary representation value of the target permission code is first1The result must be0001And0001It happens to be a readable permission code, soaccessCode&Readable == ReadablebytrueThis means that the target permission code has readable permissions.

If the first binary bit of the target permission code is not1But0Then0&1=0 ,(0|1)^0=0So bitwise and computational results must be all right.0That is to say,0000At this point0000 == 0001ComparisonsfalseThat is, the permission code is unreadable.

Similarly, it can be analyzed independently.accessCode&Writing == WritingResulttrueIt means that it can be written, otherwise it can’t be written.accessCode&Executable == ExecutableResulttrueIt means enforceable.falseIt means that it is not enforceable.

Familiar withiotaAfter mathematic calculation and bit calculation, we take advantage of the hot iron, and continue to practice in units of file size! ____________

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)
}

byteByteWith kilobytesKilobyteThe decimal units between them are1024That is to say2^10It just works.iotaLeft shift10Bits are represented by moving only once at a time, multiplied directly by10Just fine!

What about?iotaIs it amazing? Is it a little confused like me?iotaWhat on earth is this?

Baidu Translation explains to us that this product means “trace” and similar to English words.littleSame,a littleIt also means “a little bit”.

howeveriotaIn addition to representationA bit ofBesides, it seems to have self-increasing ability. That’s not true.littleThis kind of quantifier can convey the meaning.

Therefore, it is possible toiotaIt’s not the original English meaning. Maybe it’s the Greek alphabet language. It’s a standard query.24Greek alphabet and corresponding English annotations.

Capital letters A lowercase letter English pronunciation International Phonetic Alphabet Significance
Α α alpha /ˈælfə/ Angle, Coefficient, Angular Acceleration
Β β beta /’beitə/ Flux coefficient, angle, coefficient
Γ γ gamma /’gæmə/ Conductivity, Angle, Specific Heat Capacity Ratio
Δ δ delta /’deltə/ Variation, diopter, one-dimensional quadratic
Ε ε epsilon /ep’silon/ Logarithmic cardinality, dielectric constant
Ζ ζ zeta /’zi:tə/ Coefficient, azimuth, impedance, relative viscosity
Η η eta /’i:tə/ Hysteresis coefficient, efficiency
Θ θ theta /’θi:tə/ Temperature, Angle
Ι ι ℩ iota /ai’oute/ Tiny, a little
Κ κ kappa /’kæpə/ Dielectric constant, adiabatic index
λ lambda /’læmdə/ Wavelength, Volume, Thermal Conductivity
Μ μ mu /mju:/ Permeability, Fretting Friction System (Factor), Hydrodynamic Viscosity
Ν ν nu /nju:/ Magnetoresistance Coefficient, Fluid Motion Viscosity, Photon Frequency
Ξ ξ xi /ksi/ An Unknown Specific Value in Random Number (Small) Interval
Ο ο omicron /oumaik’rən/ Higher order infinitesimal function
π pi /pai/ Pi(n) denotes the number of prime numbers not greater than n.
Ρ ρ rho /rou/ Resistance Coefficient, Polar Diameter, Density in Cylindrical and Polar Coordinates
σ ς sigma /’sigmə/ Total, Surface Density, Transconductance, Normal Stress
Τ τ tau /tau/ Time constant, shear stress
Υ υ upsilon /ju:p’silən/ displacement
Φ φ phi /fai/ Flux, Angle, Lens Focus, Heat Flow
Χ χ chi /kai/ Chi-square (_2) distribution in Statistics
Ψ ψ psi /psai/ Angular velocity, dielectric flux
Ω ω omega /’oumigə/ Ohm, Angular Speed, Electrical Angle of AC

Greek letters are often used in physics, chemistry, biology, science and other disciplines, as constants or variables, unlike ordinary English variables or constants, Greek letters usually represent variables or constants with specific semantics!

Therefore,iotaIt should be the Greek alphabet.IEnglish Representation, the Variable or Constant Representationsmall,One o’clockMeaning.

When translated into natural language, this symbol represents a little bit. If it expresses the meaning of change, it is a little bit more on the original basis. If it expresses the meaning of unchanged, it should be only a little bit, that’s all.

Of course, the above are all personal guesses. More professional statements should be looked at.GoHow to Define LanguageiotaHold onCtrlKeyboard, mouse hover iniotaClick 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.

Short translation:

iotaIs a predefined identifier, representingCurrent Constantinunsigned intOfSerial numberSo0As an index.

The annotations above seem obscure and difficult to understand. If they are constants, they should be quiet as constants. Can’t they? How can we read the taste of cyclic variable index from the definition of constants?

In order to verify the conjecture, we still simulate each step with the simplest weekly conversion as an example.iotaThe value of.

const (
    // iota = 0, Mon = 1 + 0 = 1, consistent with output result 1, when iota = 1, that is, iota increases by 1
    Mon = 1 + iota
    // iota = 1, Tue = 1 + iota = 1 + 1 = 2, which corresponds to output 2, at which time iota = 2
    Tue
    // iota = 2, Wed = 1 + iota = 1 + 2 = 3, consistent with output result 3, when iota = 3
    Wed
    Thu
    Fri
    Sat
    Sun
)
// 1 2 3 4 5 6 7
t.Log(Mon, Tue, Wed, Thu, Fri, Sat, Sun)

Lieutenant GeneraliotaAs variables in a constant declaration loopiEvery statement,i++Therefore, only the initial conditions of the loop and the cyclic incremental variables need to be defined to complete the cyclic assignment.

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)

Does this correspond to the feeling?iotaIt seems to be a cyclic variable.iAmong them,Mon = 1 + iotaIt’s the initial body of the loop.Mon~SunA finite constant is the termination condition of a cycle, and each constant is the next cycle.

If one example is not enough to verify the conjecture, then another one!

const (
Readable = 1 << iota
Writing
Executable
)
// 0001 0010 0100 or 124
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)

These two examples have been preliminarily verified.iotaPossible and cyclic variablesiIt has certain relevance and can be further approached to guess.

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 10 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)

iotaAn index of a set of cyclic variables in constant initialization. When the set of variables has been initialized completely,iotaStart again, so new variablescurrentIotaThe value is0Instead of7

Therefore,iotaThe reason behind the initialization often used as a set of regular constants may be the assignment of cyclic variables.iotaFor the time being, there is no problem with this example. Whether this understanding is accurate or not remains to be further studied.GoFor further verification, one word, for reference only!

Basic Summary of Variables and Constants

  • Variable usevarKeyword declaration, constantconstKeyword declaration.
  • Variable declaration and assignment have many forms, so it is better to unify one form to avoid style inconsistency.
  • Variable types have the ability of automatic inference, but in essence they are still strong types, and there is no automatic conversion between different types.
  • Constants of a set of laws can be usediotaConstant simplification can be temporarily understood as the use of a circular way to assign variables, thus converting them into constant initialization.
  • Variables and constants have similar initialization forms. Different from other programming languages, they can assign multiple variables in a single statement, which simplifies the rules of code writing to a certain extent.
  • Any defined but unused variables or constants are not allowed to exist, since they are not needed, why declare?! No redundant design, good or bad can not be assessed for the time being, since how to design, then abide by it!

Distinctive variables and constants

Fibonacci sequence is an infinite series of incremental numbers, such as1,1,2,3,5,8,13...Starting with the third number, the latter number is always the Fibonacci sequence, which is the sum of the first two numbers.

If we start with the third number, then the first two numbers are the initial values of Fibonacci sequence, and the next two numbers are in accordance with the established law, taking the first two numbers as variables.a,bCyclic method is used to continuously push the sequence backward to obtain the specified length of the sequence.

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()
}

Although the above solution is clear and clear, it is not concise enough, at least not used.GoLanguage features. In fact, we can do better, or use it.GoLanguage features enable clearer and simpler solutions:

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()
}

Unlike the first solution, this time the variables are changed.aMove forward one bit and manufactured virtual head nodes artificially0VariablesaNext nodebPoint to the first node of the Fibonacci sequence1WithaandbProgressing backwards one after another, the nodes in the next cyclebCompared with the first method, it shortens one node.

a, b := 0, 1It’s the initial value before the cycle starts.bIt’s the first node in the Fibonacci sequence, and it’s in the process of looping.a, b = b, a+bVery clear semantics, node’saBecome a nodebNodesbyesa+bThe value of.

Isn’t it amazing that there’s no use for temporary variables to store variables here?aThe exchange and assignment of variables are directly completed without the occurrence of variable coverage in the value of ___________.

Thus it can be seen,a, b = b, a+bNot at alla=bandb=a+bIt’s amazing that the cumulative results of execution are accomplished at the same time. I don’t know.GoHow to implement simultaneous assignment of multiple variables?

If you have a small partner who knows the mystery of it, you can learn and make progress together.

If you find the above operation a little difficult to understand, then the next operation, I believe you will be familiar with, that is, the value of two variables to exchange.

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)
}

Similarly,a, b = b, aMultivariate simultaneous assignment directly completes the exchange of variables. Other programming languages usually use temporary variables to store variables in advance to achieve similar requirements.aValues to prevent variable coverage, howeverGoLanguage should be realized in the same way as ordinary people think. I have to say that this is really good!

The basic use of variables and constants is introduced through a simple Fibonacci sequence, andGoI hope I can give you an introduction.GoLanguage foundation, understanding how different it is from other programming languages and how convenient it is for our actual coding, if it can be implemented in familiar programming languagesGoLanguage design has never been an interesting thing.

Next, 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 points and the corresponding practical application.

  • There is no necessary connection between the directory where the source file is located and the package where the source file is located.package mainThe source file is not necessarily in themainNot even in the catalogue.mainCatalog.

hello.goSource files are located inhelloUnder the catalogue, andhello_word.goBe locatedmainCatalogue, but all of their packages arepackage main

  • Source file naming is not known for the time being, but test file naming must bexxx_testThe test method is namedTestXXXAmong them,GoIt naturally supports testing frameworks without additional loading of third-party class libraries.

  • The key words for declaring variables arevarThe keyword to declare a constant isconstThere are several ways to declare variables and constants, and automatic type inference can simplify them.

Generally speaking, to implement global variable declaration in other programming languagesvarLocal variable declaration:=Simplified form in which multiple variables can be assigned simultaneously.

  • A set of constants of a particular law can be used skillfullyiotaIt can be understood as the first use.iotaConstants are the first of these constants, and the other constants are initialized in turn according to the law.

GoLanguages do not have enumeration classes. They can be enumerated with a set of constants. After all, enumeration is a special constant.

The source code of this article has been uploaded to the https://github.com/snowdreams 1006/learn-go project. Interested partners can click to view it. If there are inappropriate descriptions in this article, please point out. Thank you for your comments and forwarding.

Recommended Today

Front-end core tools: yarn, NPM, and CNPM how can they be used together elegantly?

A front end that doesn’t work well with package managers is an entry-level front end that doesn’t work wellwebpackThe front end is a primary front end Three package managers can be used together, as long as you are bold enough, no problem! Recommend two articles Handwritten React scaffolding Handwritten Vue scaffolding Front-end performance optimization incomplete […]