Go language Wonderful point

Source: Internet
Author: User
Tags pow
1. Pointer (default value nil)

I, J: = 42, 2701
P: = *i//Pointer symbol * cannot be used directly on variable names that have already been declared, otherwise it will error at compile time: invalid indirect of I (type int)


P: = &i//Declare and copy pointer variable p

Fmt. PRINTLN (*P)//reads the value pointed to by the pointer variable, resulting in 42


The way the pointer is declared, such as
var IP *int/* Point int */

var fp *float32/* point to floating-point type * *


Summary: The pointer variable can only accept the memory address obtained by the & number, which is used to point to the memory stored in the address of the value of the function

Package main

Import "FMT"

func Main () {
   var a int=/   * Declare the actual variable * * *
   var IP *int/        * DECLARE pointer variable * *

   IP = &a/  * Pointer variable value is the storage address of variable A/

   FMT. Printf ("A variable's address is:%x\n", &a  )/

   * Pointer variable's storage address * *
   FMT. Printf ("IP variable stored pointer address:%x\n", IP)//

   * Use pointer access value/
   FMT.  Printf ("*ip is used to access the value stored in the memory address that the pointer variable points to:%d\n", *ip)
   
   *ip =//  * The value of the actual A is modified here is a of */
var ip2 **int ip2 = &IP/* Pointer, the memory address of memory address * * FMT. Printf (the value stored in the memory address that the pointer variable **IP2 uses to access the pointer:%d\n ", **IP2)
}
1.2. Array of pointers
Package main


Import "FMT"

const MAX int = 3

func main () {
   A: = []int{10,100,200}
   var i int
   v Ar ptr [max]*int;  for i = 0; i < Max; i++ {
      ptr[i] = &a[i]/* Integer address assignment to pointer array * * For  i = 0; i < MAX; i++ { C31/>fmt. Printf ("a[%d] =%d\n", I,*ptr[i])
   }

1.3. Structure Body Pointer
Package main

Import "FMT"

type Vertex struct {
	X int
	Y int
}

func main () {
	V: = vertex{1, 2}
  p: = &v
	p.x = 2            //The struct body field can be accessed through the structure body pointer.
	FMT. PRINTLN (P)     //Output &{2 2}
	fmt. Println (p.x)   //Output 2
	FMT. Println (v)     /output {2 2}
}
2. Construction method of initialization
Package main

Import "FMT"

type Vertex struct {
	X, Y int
}

var (
	v1 = vertex{1, 2}  //Type For Vertex
	v2 = vertex{y:1}  //default specified x:0
	v3 = vertex{}      //x:0 and y:0
	v4 = new (Vertex)   //This method cannot assign an initial value, this actually creates a struct pointer
	p  = &vertex{1, 2}//Type is *vertex
)

Func Main () {
	fmt. Println (v1, v2, v3, v4, p)//output {1 2} {0 1} {0 0} &{0 0} &{1 2}
}
you can not initialize direct assignment and output
Package main

Import "FMT"

type Vertex struct {
	X int
	Y int
}

func main () {
	var Vertex vertex< C7/>fmt. PRINTLN (vertex)//uninitialized, actually initialized new (vertex) by default. Output {0 0}
	vertex. X = 1
	vertex. Y = 2
	fmt. PRINTLN (vertex)/output {1 2}
}
3.Map Uninitialized map cannot be assigned value
Package main

Import "FMT"

type Vertex struct {
	X int
	Y int
}

func main () {
	var Asset m Ap[string] Vertex
	asset["abc" = Vertex
	fmt. PRINTLN (asset["abc"])
}
Compile times Error: Panic:assignment to entry in nil map

The normal example
Package main

Import "FMT"

type Vertex struct {
	X int
	Y int
}

func main () {
	var Asset m Ap[string] Vertex
	Asset = Make (map[string) Vertex)
	asset["abc" = Vertex fmt
	. PRINTLN (asset["abc"])
}
Change and check of map's additions and deletions
Package main

Import "FMT"

func Main () {
	m: = Make (Map[string]int)

	m["Answer"] =    //Initialize
	FMT. Println ("The Value:", m["Answer"])

	m["Answer"] =    //Modify value
	FMT. Println ("The Value:", m["Answer"])

	Delete (M, "Answer")//delete value
	FMT. Println ("The Value:", m["Answer"])
	
	if m["Answer"] = = 0 {
		fmt. Println ("nonexistent key")   //The value of the key cannot exist is 0
	}

	V, OK: = m["Answer"]//The presence of     a key is detected by a double assignment, and OK is true if the key is in M. Otherwise, OK is false, and Elem is the 0 value of the element type of the map.
	FMT. Println ("The Value:", V, "Present?", OK)
}
4.1. Slices (default value nil)------------------the length and capacity of a nil slice is 0.
Expression S[lo:hi]

Represents a slice element from lo to hi-1, with a front end and no back end.

4.2. Structural slices
Package main

Import "FMT"

func Main () {
	A: = Make ([]int, 5)
	Printslice ("A", a)        /output a len=5 cap=5 [0 0 0 0 0]
	b: = make ([]int, 0, 5)
	Printslice ("B", b)        /output B len=0 cap=5 []
	c: = B[:2]
	printslice ("C", c) 
  //output C len=2 cap=5 [0 0]
	d: = C[2:5]
	printslice ("D", D)        /output D len=3 cap=3 [0 0 0]
}

func Prints Lice (S string, x []int) {
	fmt. Printf ("%s len=%d cap=%d%v\n",
		S, Len (x), Cap (x), x)
}
4.3. Slice add element Appendvar a []int = []int{1,2,3,4,5}
A = append (a,6)
Package main

Import "FMT"

func Main () {
	var a []int
	printslice ("A", a)/            output a len=0 cap=0 []

	//AP Pend works on nil slices.
	A = append (A, 0)
	printslice ("A", a)//            output a len=1 cap=2 [0]

	//The slice grows as needed.
	A = Append (A, 1)
	Printslice ("A", a)//            output a len=2 cap=2 [0 1]

	//We can add more than one element at a time.< C14/>a = Append (A, 2, 3, 4)
	Printslice ("A", a)            //Output a len=5 cap=8 [0 1 2 3]
}

func Printslice (S Strin g, x []int) {
	fmt. Printf ("%s len=%d cap=%d%v\n",
		S, Len (x), Cap (x), x)
}
5. Traverse Range--------There are 2 return values, one is the index of the element, one is the value of the element, and 2 values can also be taken as follows
Package main

Import "FMT"

var pow = []int{1, 2, 4, 8, +, 128}

func main () {for
	I, V: = Range POW {
		FMT.  Printf ("2**%d =%d\n", I, v)
	}
	for I: = Range pow {
		pow[i] = 1 << uint (i)
	}
	for _, Value: = Range POW {
		fmt. Printf ("%d\n", Value)
	}
}
When you use range to traverse a map, the first element is the key value and the second element is the value
Package main

Import "FMT"

type ipaddr [4]byte

//Todo:add A "string () string" method to IPAddr.

Func Main () {
	Addrs: = map[string]ipaddr{
		"loopback":  {127, 0, 0, 1},
		"Googledns": {8, 8, 8, 8},
	}
  for N, A: = Range Addrs {
		fmt. Printf ("%v:%v\n", N, a)
	}
}
The top output results are
Loopback: [127 0 0 1]
googledns: [8 8 8 8]



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.