Translation Go 1.1 Introduction

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.


Because the work is too busy, has not written something. But I think it's worth it, so ...
Original: https://tip.golang.org/hg/doc/go1.1.html
The original link I have replaced, now pointing to tip most should be correct. But if it's Go 1.1 officially released six months later, I don't promise.
———— Translation Divider Line ————



Go 1.1 Introduction



Go first edition (go 1 or Go 1.0) released in March 2012, this version provides a stable go language and library. Its stability makes the Go user community and related systems thrive throughout the world. Since then, a number of "key points"--1.0.1, 1.0.2 and 1.0.3 have been released. The release of these points fixes several known bugs, but the implementation itself has not been modified.



This new release, Go 1.1, adds several important (and, of course, backward-compatible) language changes while maintaining compatibility, while the list of library changes is long (and backwards compatible), as well as the main work implemented in compilers, libraries, and run-time environments. Focus is on performance. The tests are not very precise, but there are important and sometimes dramatic performance improvements for many test programs. We believe that by upgrading the Go installation package and recompiling, many users ' programs can also make this improvement possible.

This document summarizes the changes from Go 1 to go 1.1. Although this release has some extremely rare error conditions, it must be handled when these situations occur. Running on Go 1.1 requires little modification of any code. The following describes the details; see special instructions for 64-bit integers and Unicode literals.



Changes in language



The Go Compatibility documentation ensures that programs written with the Go 1 language specification are still available and can continue to be maintained. While some of the details of the error situation have been pointed out, the refinement of the specification itself is quite interesting. It also adds some new features to the language.



Integer divided by 0



In Go 1, integers are divisible by a constant zero to produce a run-time panic:


func f(x int) int {
	return x/0
}


In Go 1.1, an integer that is divisible by a constant zero is not a legitimate program, so this is a compile-time error.



Surrogate Unicode Text



The definition of string and rune literals is refined to exclude the surrogate part from legitimate Unicode encoded values. See the Unicode section for more information.



Method value



Now Go 1.1 implements the method value, which is to bind the function to the value of a particular recipient. For example, there is a Writer value W, the expression W.write, is a method value, as a function to write to W, which is equivalent to the closure of W in the function grammar:


func (p []byte) (n int, err error) {
	return w.Write(p)
}


The method value is different from the method expression, and the method expression constructs a function from the method using the specified type; the method expression (*bufio. Writer). Write is specified with the first parameter type (*BUFIO. Writer) is equivalent to the function:


func (w *bufio.Writer, p []byte) (n int, err error) {
	return w.Write(p)
}


Update : Existing code is not affected; This change is strictly backwards compatible.



Return Requirements



Before Go 1.1, a function returns a value that must be explicitly "return" at the end of the function or call panic; This is a simple way to make the concept of a program explicit. However, there are obviously many situations where the final "return" is not necessary, for example, a function that only has a dead loop of "for".



In Go 1.1, the rules about the last "return" statement are more relaxed. It introduces the concept of a terminating statement, which guarantees that the statement is always last executed in the function. For example, in a "for" loop without a condition, there is no "if-else" statement to end in the middle through "return." Then the last statement of the function can be syntactically considered a terminating statement, without the need for a final "return" statement.



Note that this rule is purely grammatical: it does not focus on the values in the code, so there is no complex analysis.



Update : This change is backwards compatible, but the existing code with redundant "return" statements or calls to panic may need to be processed manually. This code can be usedgo vetto identify.



Changes to implementations and tools



command-line argument parsing



In the GC toolchain, the compiler and linker now use theflagsame command-line parameter parsing rules as the Go package, which runs counter to the traditional Unix parameter parsing. This can have an impact on the script that invokes the tool directly. For example,go tool 6c -Fw -Dfooit must now be written asgo tool 6c -F -w -D foo.



Integer size on a 64-bit platform



The language allows you to select an int type and a uint type of 32 or 64 bits, depending on the implementation. The previous implementation of Go was to make the int and uint 32 bits on all systems. Both the GC and GCCGO implementations now allow int and uint to be 64-bit on platforms such as amd64/x86-64. Aside from the others, the single one allows slice to allocate more than 2 billion elements on 64-bit platforms.



update : Most programs are not affected by this. Since Go does not allow implicit conversions between different numeric types, there is no program in the Compile Times error. However, those implicitly assuming that int is a 32-bit program may change in behavior. For example, this program prints a positive number on a 64-bit system, and a negative number is printed on a 32-bit system:


x := ^uint32(0) // x is 0xffffffff
i := int(x)     // i is -1 on 32-bit systems, 0xffffffff on 64-bit
fmt.Println(i)


To keep the 32-bit symbol (1 on all systems) should be replaced with the following portable code:


I: = Int (int32 (x))


Unicode



To be able to express more than 65535 of the encoded values in the UTF-16, Unicode defines the surrogate part, a range of coded values that are used only to assemble larger values, and only in UTF-16. Coded values within this surrogate range are illegal if used in any other case, such as UTF-8 encoding, or as a standalone UTF-16 encoding. For example, when encountering a rune converted to UTF-8, it is treated as a coding error and produces an alternative Rune,utf8. Runeerror, U+fffd.



This program,


import "fmt"

func main() {
    fmt.Printf("%+q\n", string(0xD800))
}


Print "\ud800" in Go 1.0, but print "\UFFFD" in Go 1.1.



Half surrogate Unicode values are now illegal in rune and string constants, so constants such as "\ud800" and "\ud800" are now rejected by the compiler. When writing to a separate UTF-8 encoded byte, the string can still be created, such as "\xed\xa0\x80". However, when the string is decoded as a rune sequence, such as in the range loop, it only generates UTF8. The Runeerror value.



The Unicode byte order allows U+fffe and U+feff to appear as the first character of the Go source code under UTF-8 encoding. Although it is completely unnecessary in UTF-8 encoding, which is not set in byte order, some editors add it as "magic value" to identify a UTF-8 encoded file.



update : Most programs are not affected by substitution changes. Programs that are based on old behavior should be modified to avoid problems. The change in byte order identification is strictly backwards compatible.



GC Compilation



The stack layout of the function parameters in the GC Toolchain has changed based on changes such as int to 64 bits and some other variations. A function written using the assembly requires at least one frame pointer offset.



Update : Thego vetcommand now checks to see if the assembly-implemented function matches the function prototype of Go.



Changes to the GO command



To get a better experience for a new go user, the Go command makes a few changes.



First, when compiling, testing, or running the go code, the Go command gives more details of the error message, and lists the search path when a package cannot be located.


$ go build foo/quxx
can't load package: package foo/quxx: cannot find package "foo/quxx" in any of:
        /home/you/go/src/pkg/foo/quxx (from $GOROOT)
        /home/you/src/foo/quxx (from $GOPATH)


Second,go getwhen the command is no longer allowed to download the package source code, $GOROOT as the default destination path. To usego geta command, you must have a legitimate $GOPATH.


$ GOPATH= go get code.google.com/p/foo/quxx
package code.google.com/p/foo/quxx: cannot download, $GOPATH not set. For more details see: go help gopath


Finally, as a result of the previous changes, thego getcommand will give an error when the $GOPATH and $GOROOT are set to the same value.


$ GOPATH=$GOROOT go get code.google.com/p/foo/quxx
warning: GOPATH set to GOROOT (/home/User/go) has no effect
package code.google.com/p/foo/quxx: cannot download, $GOPATH must not be set to $GOROOT. For more details see: go help gopath


Changes to the Go Test command



go testThe command no longer deletes binary content when performing a performance test, making it easier to analyze performance tests. The implementation is set at run time with the-c parameter.


$ go test-cpuprofile cpuprof.out mypackage


go testafter running, the mypackage.test will remain in the directory.



go testCommands can now report where Goroutine is blocking test information, that is, where they have been waiting for an event, such as a channel communication.-blockprofilego testThis information is displayed when an open blocking test is used. Run forgo help testmore information.



Changes to the Go Fix command



The fix command is typicallygo fixexecuted to no longer provide the ability to upgrade from a previous version of Go1 to the go 1 API. If you want to upgrade the code before go 1 to go 1.1, you should first use the Go 1.0 toolchain to convert the code to go 1.0.



Performance



The performance of the code compiled with the GC toolset for GO 1.1 should be significantly improved for most go applications. In general, compared to Go 1.0, about 30%-40% of the ascension, sometimes even higher, of course, will be lower than this value, or even no ascension. For tools and libraries, there are too many small performance-driven changes that cannot be listed here. However, the following major changes are still necessary to note:


    • The GC compiler generates good code in most cases, especially floating-point values under the 32-bit Intel architecture.
    • The GC compiler makes more connections, including some operations at run time, such as Append and interface transformations.
    • The Go map has a new implementation, with significant improvements in memory replication and CPU time.
    • Garbage collection enables more parallelism, which reduces the latency of programs that run in a multi-CPU environment.
    • Garbage collection is also more accurate, which adds a bit of CPU time overhead, but greatly reduces the heap size, especially in 32-bit architectures.
    • By tightly combining the runtime and network libraries, there is less context switching required for network operations.


Changes to the standard library



Bufio. Scanner



There are several ways to get text input in the Bufio package, Readbytes, ReadString, and special ReadLine, which are somewhat too complex for simple purposes. In Go 1.1, a new type, Scanner, is added to make it easier to handle simple tasks such as reading input sequences by line or space-delimited words. It ends with input errors such as entering a long, problematic row, and provides a simple default behavior: row-based input, with each row rejecting delimited identities. Here the code shows to enter one line at a time:


scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
    fmt.Println(scanner.Text()) // Println will add back the final '\n'
}
if err := scanner.Err(); err != nil {
    fmt.Fprintln(os.Stderr, "reading standard input:", err)
}


The behavior of the input can be controlled by a function to control each part of the input (see Splitfunc's documentation), but it may still be necessary to have the original interface for complex problems or for continuous error delivery.



Net



Before the protocol-specific parser in the net package, the network name passed in is very loose. Although the documentation clearly states that for RESOLVETCPADDR legitimate network names are only "TCP", "TCP4" and "TCP6", the implementation of Go 1.0 is accepted for any string. The implementation of Go 1.1, if the network name is not in these strings, will return an error. This is also true for other protocol-specific parsers, RESOLVEIPADDR, resolveudpaddr, and resolveunixaddr.



Prior to the implementation, Listenunixgram returns a udpconn as the endpoint of the receive connection. In the implementation of Go 1.1, replace with Unixconn, which allows to read and write with its readfrom and WriteTo methods.



Data Structures ipaddr, TCPADDR, and udpaddr add a new string field called Zone. Because of the new field, a composite grammar with no labels (for example, net) is used. Tcpaddr{ip, port}) code in place of the tagged grammar (net. Tcpaddr{ip:ip, Port:port}) will make an error. The compatibility rules for Go 1 allow this change: The client code must use a tagged grammar to avoid this damage.



update : To correct the damage caused by new struct fields,go fixThese types of code will be rewritten to add tags. More generally, itgo vetwill identify all the compound grammars that should use the field labels.



Reflect



The reflect package has several significant improvements.



It is now possible to return a "select" statement with the reflect package; see SELECT and selectcase for more details.



The new method Value.convert (or Type.convertibleto) provides a function of the Go conversion and type assertion operation (or detection of this possibility) on a Value.



The new function Makefunc creates a wrapper function that makes it easier to call a function on an existing Value, and can be used for the conversion of standard Go parameters, such as passing an int to interface{}.



Finally, the new functions chanof, MAPOF, and sliceof can construct a new type from an existing type, such as constructing []t] with only a T.



Time



The previous time packages are accurate to microseconds on FreeBSD, Linux, NetBSD, OS X, and OpenBSD. Go 1.1 implementations on these operating systems can be accurate to nanoseconds. The program uses subtle accuracy to write to the external and then read out, if the original value is overwritten, it will produce a loss of precision. Time has two new methods, Round and Truncate, that can be used to remove the accuracy of the data before writing to the external store.



The new method Yearday returns the unique integer ordinal of the day of the specified time value in a year.



The timer type has a new method, Reset, that expires the timer after the specified interval.



Finally, a new function, Parseinlocation, is similar to an existing parse, but ignores time zone information in the parsed string and uses the incoming location (time zone) to parse it. This function solves the common confusion in the time API.



Update : For those code that uses the lower-precision external format to read and write time, the new method should be modified.



EXP Old code tree moved to Go.exp and Go.text child repository



In order for users using the binary release to access more easily when needed, the exp and old source trees not included in the binary release are moved to the new child repository Code.google.com/p/go.exp. For example, if you want to access the SSA package, perform


$ go Get Code.google.com/p/go.exp/ssa


Then in the Go code,


Import "Code.google.com/p/go.exp/ssa"


The old package Exp/norm also migrated to the new repository Go.text, which contains the Unicode APIs being developed and other text-related packages.



Small changes to the library



The following list lists minor changes to the library, most of which are enhancements. For each change, see the package-related documentation for more information.

The bytes package has two new functions, TrimPrefix and TrimSuffix, which are self-explanatory. Similarly, the Buffer type has a new method, Grow, that provides some ability to control the internal memory allocation of the cache. Finally, the Reader type now has a WriteTo method, so it also implements the io.WriterTo interface.
crypto / hmac has a new function, Equal, to compare two MACs.
The crypto / x509 package now supports PEM blocks (see DecryptPEMBlock for an example) and a new function ParseECPrivateKey for parsing elliptic curve private keys.
The database / sql package has a new Ping method on the DB type to check the health of the connection.
database / sql / driver has a new Queryer interface so Conn can make some performance improvements by implementing that interface.
The encoding / json package's Decoder has a new method, Buffered, to provide access to the remaining data in its cache, as well as a new method, UseNumber, which decodes a value into a new type Number, which is actually a string, rather than a float64.
The encoding / xml package has a new function, EscapeText, for outputting escaped XML, and Encoder's method, Inden, is designed to output indented formats.
In the go / ast package, the new type CommentMap and its associated methods make it easier to separate and process comments from Go programs.
In the go / doc package, the parser can now better track some identifiers such as TODO, and the godoc command can optionally filter or render this information based on the -notes parameter.
A new package, go / format, provides programs with a more convenient way to get gofmt's formatting capabilities. It has two functions, Node is used to format Go's parse Node, and Source is used to format Go's source code.
The "noescape" feature that is not documented in the html / template package and is only partially implemented is removed; programs that rely on it are broken.
The io package now exports the io.ByteWriter interface to meet common functions such as writing one byte at a time.
The log / syslog package now provides better system-specific logging capabilities.
The math / big package's Int types now have methods MarshalJSON and UnmarshalJSON for converting to and from JSON format. Similarly, Int can now be converted directly to or from uint64 via Uint64 and SetUint64, and Rat via Float64 and SetFloat64.
The mime / multipart package writer has a new method, SetBoundary is used to define the boundary separation of the package output.
The ListenUnixgram function of the net package changes the type of the return value: it now returns UnixConn instead of UDPConn, which is obviously a bug in Go 1.0. So this API change fixes a bug, which complies with Go 1 compatibility rules.
The net package contains a new function, DialOpt, which adds options to Dial. Each option is reflected in the new interface DialOption. The new functions Deadline, Timeout, Network, and LocalAddress will, of course, have a DialOption.
net adds support for local IPv6 addresses with zone authentication, such as fe80 :: 1% lo0. The address structures IPAddr, UDPAddr, and TCPAddr record area information in a new field. Those functions that require string formatting as addresses, such as Dial, ResolveIPAddr, ResolveUDPAddr, and ResolveTCPAddr now accept formats with zone validation.
The net package adds LookupNS as a parsing function. LookupNS returns an NS records based on the host name.
The net package adds the read and write methods of the specified protocol to IPConn (ReadMsgIP and WriteMsgIP) and UDPConn (ReadMsgUDP and WriteMsgUDP). There is also a special version of PacketConn's ReadFrom and WriteTo methods that provide the ability to access out-of-band data for a packet.
net adds methods to UnixConn to half-close the connection (CloseRead and CloseWrite), which matches TCPConn's existing methods.
The net / http package contains several new additions. ParseTime parses a time string and tries several common HTTP time formats. The PostFormValue method of Request is similar to FormValue, but ignores the URL parameter. The CloseNotifier interface provides a mechanism for the server-side handler to discover that the client is disconnected. The ServeMux type now has a Handler method to access the Handler's path without executing it. Transport can now cancel an ongoing request via CancelRequest. Finally, when Response.Body is closed before it is fully processed, Transport will now be more optimistic about closing TCP connections.
The new net / http / cookiejar package provides basic functionality for managing HTTP cookies.
The net / mail package has two new functions, ParseAddress and ParseAddressList, to parse RFC 5322 formatted addresses into the Address structure.
The client type of the net / smtp package has a new method, Hello, for sending HELO or EHLO messages to the server.
net / textproto has two new functions, TrimBytes and TrimString, which are used to cut back and forth spaces only in ASCII.
The new method os.FileMode.IsRegular makes it easier to know if a file is a normal file.
image / jpeg can now read pre-loaded JPEG files and handle certain subsampling configuration information.
The regexp package now supports Unix native leftmost longest matching via Regexp.Longest, while Regexp.Split uses a separator defined by regular expressions to split strings into groups.
runtime / debug has three new functions on memory usage. The FreeOSMemory function triggers garbage collection and attempts to return unused memory to the operating system; ReadGCStats obtains the controller's statistics; and SetGCPercent provides a programmable way to control the frequency of the controller's execution, including permanently prohibiting its execution.
The sort package has a new function, Reverse. As a wrapper to the parameter that calls sort.Sort, the sorting results can be reversed by calling Reverse.
The strings package has two new functions, TrimPrefix and TrimSuffix, and the Reader.WriteTo method, so Reader now implements the io.WriterTo interface.
There are many updates to the syscall package, including hardening system calls for each supported operating system.
The testing package can now use the AllocsPerRun function and the AllocsPerOp method of BenchmarkResult to automatically generate memory allocation statistics in performance tests. There are also Verbose functions to check the status of command line arguments to -v, and new methods Skip for testing.B and testing.T to simply skip unnecessary tests.
In the text / template and html / template packages, templates can now use parentheses to group character sequences, which simplifies the process of creating complex character sequences. TODO: Link to an instance. At the same time, as part of the new parser, the Node interface has two methods to provide better error reporting. This also follows Go 1 compatibility rules. Since this interface is explicitly expected to be used only by the text / template and html / template packages, and its security mechanism guarantees this, no code should be affected.
In the unicode / utf8 package, the new function ValidRune reports whether a rune is a legal Unicode encoding value. To ensure legality, the value of rune must be in the range and cannot be a half surrogate.
The implementation of the unicode package has been updated to Unicode 7.2.0.
———— translation divider ————
Fortunately, a few painful tablets suppressed for a few days. It just seems that the pain can't solve the fever problem. Back home was forced to rest ...
The translation was delayed until today, and I believe that the quality must be very poor, very poor ...
Let's see for yourself! Leave a message to me, I am hibernating.
If I don't come back tomorrow morning, please pray to God of Gopher, I must have been to that beautiful place.


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.