Compound literal in Go

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed. [] (https://raw.githubusercontent.com/studygolang/gctt-images/master/composite-literal/1_ Tm61vtlvvl2ywti6uuylog.png) literals in the source code can describe fixed values like numbers, strings, booleans, and so on. Like Go and JavaScript, Python, even composite types (arrays, dictionaries, slices, structs) also allow the use of literals. Golang's compound literal expression is also convenient and concise, and can be implemented using a single syntax. In JavaScript it is this: "' Javascriptvar numbers = [1, 2, 3, 4]var thing = {name:" Raspberry Pi ", Generation:2, Model:" B "}" ' There is a similar syntax in Python: ' ' pythonelements = [1, 2, 3, 4]thing = {' name ': ' Raspberry Pi ', ' Generation ': 2, ' model ': ' B '} ' ' in Go Also similar (here are some places to be flexible): "' goelements: = []int{1, 2, 3, 4}type Thing struct {name stringgeneration intmodel string}thing: = thing{ "Raspberry Pi", 2, "B"}//or directly using struct's item name Thing = Thing{name: "Raspberry Pi", Generation:2, Model: "B"} "" except for types other than dictionary type, keys are optional , easy to understand without ambiguity: * For structs, the key is the item name * for arrays or slices, the key is the index key is not a literal constant, it must be a constant expression, so this is wrong: "' Gof: = func () int {return 1}elements: = []s tring{0: "Zero", F (): "One"} "this will cause a compilation exception--" Index must be non-negative integer constant ". The constant expression or literal is legal: "' goelements: = []string{0: "Zero", 1: "One", 4/2: "Both"} "' compiles everything goes well. Duplicate keys are not allowed: "' goelements: = []string{0:" Zero ", 1:" One ", 4/2:" One ", 2:" also "}" "will be reported at compile time" duplicate index in array lit Eral:2 "Exception information. This also applies to structs: "' Gotype S struct {name string}s: = s{name:" Michał ", Name:" Michael "}" ' Compiled result is "duplicate field name in struct Literal:name "error. The corresponding literal must be assigned to an item of the corresponding key, element, or struct. More about the assignable content can be seen in the ["Go language assignable"] (https://studygolang.com/articles/12381) article. # # struct for the item defined by the struct type, here are two or three rules when creating an instance. Like the code snippet below, the struct definition must specify the name of the inner item, and if you use a name other than those defined, an error will occur at compile time: "Unknown s field ' name ' in struct literal": ' Gotype s struct { Age Int8}s: = S{name: "Michał"} "if the first literal has a corresponding key, then the literal must have a corresponding key, the following is not reasonable:" ' Gotype s struct {name stringage int8}s: = S{name: "Michał", 29} "like this, the compiler throws an exception" mixture of Field:value and value initializers ", which can be corrected by omitting the key corresponding to all elements in the struct. "' Gos: = s{" Michał ", 29}" but there is an additional restriction: the order of the literals must be consistent with the order of the items as defined by the struct. A struct must be initialized with a key: a value or a value, and it does not mean that we must assign each item in the struct. The ignored items will be assigned a value of 0 for the item type by default: ' ' Gotype S struct {name stringage int8}s: = s{name: ' Michał '}fmt.Printf ("% #v \ n", s) ' Output: ' ' Gomain. S{name: "Michał", age:0} "only when the struct is initialized with the key: value, there will be a default assignment of 0 values:" "Gos: = s{" Michał "}" the notation is not compiled, it throws an exception "too few values in struct initializer ". This error is more secure for the programmer when a new item is added to a literal-assigned item in the struct-if, in this struct, a string type named "title" is added to the "name" entry, the value "Michał" will be considered a "title "And the problem is difficult to find out. If the struct literal is null, then each item within the structure is assigned a value of 0: ' ' gotype Employee struct {Department stringposition string}type S struct {name stringage Int8employee}main. S{name: "", age:0, Employee:main. Employee{department: "", Position: ""} "last rule, the assignment of the struct is related to [Export label] (https://studygolang.com/articles/12809) (in short, Literals are not allowed to assign values to non-exported items) # # arrays and slice arrays or slices of elements are indexed, so literally the key must be an integer constant expression. For an element without a key, the key will be assigned a value of the previous element index plus one. Literally, the key (index) of the first element is set to zero by default if it is not assigned a value. "' Gonumbers: = []string{" A "," B ", 2 << 1:" C "," D "}fmt. Printf ("% #v \ n", numbers) []string{"A", "B", "", "", "C", "D"} "the number of assigned elements can be less than the length of the array (the ignored element will be assigned a value of 0):" ' Gofmt. Printf ("% #v \ n", [3]string{"foo", "Bar"}) [3]string{' foo ', ' Bar ', ' '} ' does not allow the assignment of an out-of-range index, so the following lines of code are invalid: ' ' [1]string{' foo "," Bar "}[2]string{1:" foo "," bAr "}" can be used by using three dots (... ) to save the programmer from declaring the length of the array, the compiler obtains it by adding one of the index's maximum value: "' goelements: = [...] String{2: "foo", 4: "Bar"}fmt. Printf ("% #v, length=%d\n", Elements, Len (elements)) "Output:" "[5]string{" "," "", "foo", "", "Bar"}, length=5 " The slices are basically the same as the previous array contents: "' goels: = []string{2:" foo ", 4:" Bar "}fmt. Printf ("% #v, length=%d, capacity=%d\n", Els, Len (ELS), Cap (ELS)) ' Results: ' []string{' "", "", "foo", "", "Bar"}, Length=5, Capacity=5 ' # # Dictionaries in addition to replacing the length of the array with the key type, the syntax and arrays of dictionary literals are very similar. "' Goconstants: = map[string]float64{" Euler ": 2.71828," PI ":. 1415926535}" # # shortcut if as a dictionary key or array, slice, The literal type of the dictionary element is consistent with the type of the key or element, so for brevity, this type can be omitted: "' gocoords: = Map[[2]byte]string{{1, 1}:" One One ", {2, 1}:" One One "}type Engineer struct {name stringage byte}engineers: = [...] engineer{{"Michał", {"John", 25} "" Also, if the key or element is a pointer type, &t can also be omitted: "' goengineers: = [...] *engineer{{"Michał", {"John", 25}}fmt. Printf ("% #v \ n", engineers) ' Output: ' ' [2]*main. engineer{(*main. Engineer) (0X8201CC1E0), (*main. Engineer) (0x8201cc200)} "# # Resources https://golang.org/ref/sPec#composite_literals

via:https://medium.com/golangspec/composite-literals-in-go-10dc62eec06a

Author: Michałłowicki Translator: Yiyulantian proofreading: polaris1119

This article by GCTT original compilation, go language Chinese network honor launches

This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove

529 Reads
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.