Transfer mode function parameters and variables scope

Arguments passed by:

basic introduction:

  When we explain the function precautions and usage details, we have talked about value types and reference types, here we summarize it in the system, because it is heavy and difficult, the default value type parameter is passed by value, and the default reference type parameter is passed by reference .

Two ways of passing ways:

  1) passed by value
  2) pass by reference

  In fact, whether it is passed by value or passed by reference, a copy passed to the function are variable, except that the value passed is a copy of the value, passed by reference is a copy of an address, in general, high efficiency copy the address, because a small amount of data, and copies the value of the data determines the size of the copy, the larger the data, the lower the efficiency.


Value types and reference types:

  1) Value Type: series of basic data types int, float series, bool, string, struct arrays and structures
  2) reference types: pointer, slice sections, map, pipes chan, interface is a reference type and the like

 

Variable scope:

Description:

1) declared inside functions / defined variable called local variables, the scope is limited to the internal function

test FUNC () {
  // Name and scope of age on the test function only within
  age: 10 =
  Name: = "Tom ~"
}

main FUNC () {
  // This is not the function of the above variables call.
}


2) external function declaration / definition of a variable called global variables, scopes are valid for the entire package, if it is the first letter is capitalized, then the scope is the entire program effective.

package main
import (
  "fmt"
)

var age int = 50
var Name string = "jack~"

test FUNC () {
  // Name and scope of age on the test function only within
  age: 10 =
  Name: = "Tom ~"
  fmt.Println ( "= age", age) // 10
  fmt.Println ( "Name = ", the Name) // Tom ~
}

func main() {
  fmt.Println("age = ", age)   //50
  mt.Println("Name = ", Name)   //jack~

  test()
}


3) If the variable is in a block of code, such as for / if, then the scope of this variable in the code block.

  i for: = 0; i <= 10; i ++ {
    fmt.Println ( "i =", i)
  }
  // fmt.Println ( "i =", i) here not call for the loop variable i

Exercises:

Thoughts: The following code outputs what?

Age = 20 // int var the ok
the Name: = "tom" // This sentence is equivalent to executing the following two var Name string Name = "tom" So will complain at compile time, the assignment statement is not in function in vitro.
main FUNC () {
  fmt.Println ( "name", the Name)
}

 

Guess you like

Origin www.cnblogs.com/green-frog-2019/p/11355166.html