Go? Go! (2) Go features

Source: Internet
Author: User
Document directory
  • Basic Types in go

Some good information on the internet is posted with links:

Http://www.cnblogs.com/AllenDang/archive/2012/03/03/2378534.html

Http://www.infoq.com/articles/google-go-primer

The author selects some features that I think are useful to anyone.

Variable definition

The most basic variable declaration and initialization of go:

var sum int // Just a declarationvar total int = 42 // A declaration with initialization

Here, the reason for writing the type below is to avoid int * A and B in C; such a definition actually has different types of A and B (A is a pointer, B is an integer ).

The variable definition of Go has the function of automatically deriving categories. comrades who are familiar with the script certainly do not think that name: = "gogogogo" is a cool definition + initialization. However, this is indeed an improvement for a non-explanatory language like go.

In addition, you can use the following method to declare multiple variables at a time:

VaR (

    i, j int
    s string    u, v, s = 2.0, 3.0, "bar"

)

Conditional expressions and loop statements of Go

The conditional expression of go is a C expression without parentheses, which can be written as follows:

If blablabla {

}

In addition, go inherits the methods that C can execute in if, for example, if (A = function (), a) Blablabla. In go, it only replaces the comma with a semicolon;

The loop Statement of go only supports one for statement, and there is no way to write the loop of do while at least once in GO!

(Here is a nonsense plug-in that supports the go language VIM: http://www.vim.org/scripts/download_script.php? Src_id = 11734)

For can be used in go as follows:

For a <B {}

For I: = 0; I <10; I ++ {}

For I: = range ("hello "){}

For {}

The range version is very good, reaching the scripting language level. It is a combination of Perl and python, for example, traversing a map structure (which will be detailed below ):

Package main import "FMT" func main () {FMT. println ("Hello, world") _ map: = map [String] int {"hit": 1, "PKU": 2} For I, value: = range _ map {FMT. println (I, value )}}

At the end of this part, let's talk about the switch statement in go. Using the switch as the axis of the loop part is the absolute value. The switch statement in go has the following features:

  1. Cases can be comma-separated lists of values, and fall-through is no longer the default behavior
    You can use commas (,) to separate the cases, and the downstream passthrough is no longer the default action. This feature means you can write the following statement:
    VaR result int
    Switch byte {
    Case 'A', 'B ':
    Result = 1
    Default:
    Result = 0
    }
    See? No break at all
  2. Go switches can match on much more than integers and
    Characters. Any valid expression can be the value of a case statement
    Switch can use a valid conditional expression in go as the most case condition ~~ For example:
    Switch result: = calculate (); true {
    Case result <0:
    /* Negative */
    Case result> 0:
    /* Positive */
    Default:
    /* Zero */
    }
    However, do not forget the true value after the switch ~
In my opinion, the Go function is a little cool. Why? Because its braces are not placed in the second line t_t, The go function is also characteristic:
  • Use the keyword func to indicate the Function Identity func fun (){}
  • Instead of defining the error type, use func sum (a, B INT) int {return a + B}
  • Returns multiple values in the penultimate axis. For example, func multireturn (a, B INT) (INT, INT) {return a, B}
    This part does not exist in C. Here we will describe it in detail:
    When multiple values are returned, the returned value can also be a named variable:
    Func divide (a, B INT) (quotient, remainder INT ){
    Quotient = A/B
    Remainder = A % B
    Return
    }
    Because of this feature, you no longer need to use the order of parameters and whether the parameters have the const feature in C ++ to distinguish whether they are input parameters or output parameters, you can use a higher-end return value processing method:
    If result, OK: = moremagic (); OK {
    /* Do something with result */
    }
    The last parameter of the function can always return a bool value to determine whether the current function correctly returns data.
  • The finale is coming! An anonymous function can exist in go! Really awesome, you don't have to add _ in front of the internal functions, even if you lose the fun of installing B :)
    Func makeadder (x INT) (func (INT) int ){
    Return func (y int) int {return x + y} // look at me! Am I hot? Wanna a try?
    }
    Func main (){
    Add5: = makeadder (5)
    Add36: = makeadder (36)
    FMT. println ("the answer:", add5 (add36 (1) // => the answer: 42
    }
Basic Types in go

Go and C are compared with some new products (why is the sum of C compared... In fact, these new products are included in the script, but there is always one. However, these new products appear in non-Explanatory languages. They are indeed new products, okay ...), Array, Unicode string, slice (stolen from Perl ?) And map.

  • Array: the array in go is the same as that in C and is not dynamic. Their size is part of their type and is determined by the compiler. Do not describe
  • Slice: the translation in Perl is a slice, which is also referenced here. The meaning of this data structure is as follows: it is a fragment of an array. The following are some defining methods:
    /* Construct a slice on ary that starts at S and is Len elements long */
    S1: = ary [s: Len]

    /* Omit the length to create a slice to the end of ary */
    S2: = ary [s:]

    /* Slices behave just like arrays */
    S [0] = ary [s] // => true

    // Changing the value in a slice changes it in the array
    Ary [s] = 1
    S [0] = 42
    Ary [s] = 42 // => true

    The segment of the array that the slice references can be changed by assigning a new slice to the same variable (this is not very good translation, the approximate meaning is that the part of the number array referenced by the slice can be assigned a new value to the original variable for change... The following are some practical examples ):
    /* Move the start of the slice forward by one, but do not move the end */
    S2 = S2 [1:]
    /* Slices can only move forward */
    S2 = S2 [-1:] // This is a compile Error
    You can try the following code to see the result:
    STR: = "hello"
    S: = STR [2:]
    FMT. println (S, STR)
    S = s [1:]
    FMT. println (S, STR)

    The Slice length can be changed as long as it does not exceed the maximum length of the referenced array. To put it bluntly, Arrays can be used more effectively. You can use the built-in cap function to obtain the slice capacity.
    The following is a simple example:
    A: = [...] int {1, 2, 3, 4, 5} // The... means "whatever length the initializer has"
    Len (a) // => 5

    /* Slice from the middle */
    S: = A [2: 4] // => [3 4]
    Len (s), Cap (s) // => 2, 3

    /* Grow the slice */
    S = s [0: 3] // => [3 4 5]
    Len (s), Cap (s) // => 3, 3

    /* Cannot grow it past its capacity */
    S = s [0: 4] // This is a compile Error
    Often, a slice is all that is needed for a program. in that case, a programmer need not have an array at all. go offers two ways to make slices directly without ever referencing the underlying storage:
    Speaking of this, programmers who use the go language can discard the array. Slicing has already met the vast majority of requirements.

    /* Literal constant slicing */
    S1: = [] int {1, 2, 3, 4, 5}

    /* Empty (all zero values) Empty slice array, which can be generated using the built-in make function */
    S2: = make ([] int, 10) // cap (S2) = Len (S2) = 10

  • Map: C is the most scarce basic data structure. As for how to use it, the code is waiting:
    m := make(map[string] int) // A mapping of strings to ints/* Store some values */m["foo"] = 42m["bar"] = 30/* Read, and exit program with a runtime error if key is not present. */x := m["foo"]/* Read, with comma-ok check; ok will be false if key was not present. */x, ok := m["bar"]/* Check for presence of key, _ means "I don't care about this value." */_, ok := m["baz"] // ok == false/* Assign zero as a valid value */m["foo"] = 0;_, ok := m["foo"] // ok == true/* Delete a key */m["bar"] = 0, false_, ok := m["bar"] // ok == false

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.