Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the new features of Go 1.1

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what are the new features of Go 1.1". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what are the new features of Go 1.1"?

Introduction to Go 1.1

Go * * version (Go 1 or Go 1.0 for short) was released in March 2012 and provides a stable Go language and libraries. Its stability allows Go user communities and related systems around the world to thrive. Since then, several "key points" have been released-1.0.1, 1.0.2 and 1.0.3. The release of these points fixes several known bug, but no changes are made to the implementation itself.

This new release, Go 1.1, adds a number of important (of course, backward compatible) language changes while maintaining compatibility, while the list of library changes is long (and backward compatible), as well as the main work implemented in compilers, libraries, and runtime environments. The focus is on performance. Testing is not very accurate, but there are important and sometimes dramatic performance improvements for many test programs. We believe that many users' programs will also be able to experience this improvement by upgrading the Go installation package and recompiling it.

This document summarizes the changes from Go 1 to Go 1.1. Although there are some extremely rare errors in this release, they must be addressed when they occur. Running under Go 1.1, almost no code changes are required. Details are described below; see special instructions for 64-bit integers and Unicode text.

A change in language

The Go compatibility documentation ensures that programs written in the Go 1 language specification can still be used and can continue to be maintained. Although some detailed errors have been pointed out, the refinement of the specification itself is quite interesting. At the same time, some new features of the language have been added.

Integer divided by zero

In Go 1, dividing an integer by a constant zero produces a run-time panic:

Func f (x int) int {return xamp0}

In Go 1.1, it is not legal to divide an integer by a constant zero, so this would be a compile-time error.

Substitute Unicode text

The definition of string and rune text is refined to exclude the substitute part from the legal Unicode code value. See the Unicode section for more information.

Method value

Now Go 1.1 implements the method value, that is, binding the function to the value of a specific recipient. For example, there is a value w of Writer, the expression w.Write, which is a method value as a function for writing to w; this is equivalent to closing w in a function grammar:

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

The method value is different from the method expression, which constructs a function from the specified type; the method expression (* bufio.Writer). Write is equivalent to * * functions with a parameter type specified as (* bufio.Writer):

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

Update: existing code is not affected; this change is strictly backward compatible.

Return requirements

Prior to Go 1.1, a function that returned a value had to explicitly "return" or call panic; at the end of the function. This was an easy way to make the program clear about the concept of the function. However, there are obviously many situations where "return" is not necessary, for example, a function with only an endless loop "for".

In Go 1.1, the rules for the "return" statement of * * are more relaxed. It introduces the concept of a termination statement, which ensures that the statement is always executed in the function. For example, in an unconditional "for" loop, there is no "if-else" statement to end with "return" in the middle. Then a statement of the function can be considered syntactically as a termination statement without the need for a "return" statement of *.

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

Update: this change is backward compatible, but existing code with extra "return" statements or calls to panic may need to be handled manually. These codes can be identified by go vet.

Changes to implementations and tools

Command line parameter parsing

In the gc toolchain, compilers and linkers now use command-line parameter parsing rules consistent with Go's flag package, which runs counter to traditional Unix parameter parsing. This may have an impact on scripts that invoke the tool directly. For example, go tool 6c-Fw-Dfoo must now be written as go tool 6c-F-w-Dfoo.

Integer size on 64-bit platform

The language allows you to choose the int type and the uint type to be 32 or 64-bit depending on the implementation. The previous implementation of Go made int and uint 32-bit on all systems. Now both gc and gccgo implementations make int and uint 64-bit on platforms such as AMD64/x86-64. If nothing else, this alone allows slice to allocate more than 2 billion elements on 64-bit platforms.

Update: most programs will not be affected by this. Since Go does not allow implicit conversions between different digital types, no program is compiling errors. However, programs that implicitly assume that int is 32-bit may change their behavior. For example, this program prints positive numbers on 64-bit systems and plural numbers on 32-bit systems:

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

To preserve the 32-bit symbol (- 1 on all systems), you should replace it with the following portable code:

I: = int (int32 (x))

Unicode

In order to be able to express more than 65535 of the coded values in UTF-16, Unicode defines an alternative part, a range of coded values that is only used to assemble larger values, and only in UTF-16. It is illegal for coding values within this substitution range to be used in any other case, such as as UTF-8 encoding or as independent UTF-16 encoding. For example, when it comes to converting a rune 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 of the substitute Unicode value is now illegal in both rune and string constants, so constants such as "\ ud800" and "\ ud800" are now rejected by the compiler. When writing bytes encoded as independent UTF-8, such strings can still be created, such as "\ xed\ xa0\ x80". However, when this string is decoded as a rune sequence, such as in a range loop, it only generates a utf8.RuneError value.

Unicode byte order allows U+FFFE and U+FEFF to appear as * * characters of Go source code under UTF-8 encoding. Although it is completely unnecessary in UTF-8 encodings where the byte order is not set, some editors add it as a "magic value" to identify a UTF-8-encoded file.

Update: most programs are not affected by substitution changes. Programs based on old behaviors should be modified to avoid problems. Changes in byte order identification are strictly backward compatible.

Gc assembly

Based on changes such as int to 64-bit and other changes, the stack layout of function parameters in the gc toolchain has changed. Functions written in assembly require at least one frame pointer offset.

Update: the go vet command can now check whether functions implemented in assembly match Go's function prototype.

Changes to the go command

In order to give new Go users a better experience, the go command has made several changes.

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

$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, when the go get command no longer allows you to download the package source code, use $GOROOT as the default destination path. To use the go get command, you must have a legal $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

* as a result of previous changes, the go get command reports an error when $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

The go test command no longer removes binaries during performance tests to make it easier to analyze performance tests. In implementation, the-c parameter is set at run time.

$go test-cpuprofile cpuprof.out mypackage

After go test runs, mypackage.test will remain in the directory.

The go test command can now report test information about where goroutine is blocked, that is, where they have been waiting for an event, such as an channel communication. This information is displayed when the blocking test for go test is turned on with-blockprofile. Run go help test for more information.

Changes to the go fix command

The fix command is usually executed as go fix and no longer provides the ability to upgrade to Go1 API from previous versions of Go1. If you want to upgrade the code prior to Go 1 to Go 1.1, you should first use the toolchain of Go 1.0 to convert the code to Go 1.0.If you want to upgrade the code before Go 1, you should first use the toolchain of Go 1.0.

Performance

The performance of code compiled with the gc toolset of Go 1.1 should improve significantly for most Go programs. Generally speaking, compared with Go 1.0, there is a 40% increase of about 30%, sometimes even higher, of course lower than this value, or even no improvement. There are too many small performance-driven changes for tools and libraries to list them all here. However, the following major changes need to be noted:

The gc compiler generates good code in most cases, especially floating-point values under the 32-bit Intel architecture.

The gc compiler does more inlining, including some operations at run time, such as append and interface transformations.

Go's map has a new implementation, with significant improvements in memory replication and CPU time.

Garbage collection implements more parallelism, which reduces the latency of programs running in a multi-CPU environment.

Garbage collection is also more accurate, which increases a little bit of CPU time overhead, but greatly reduces the heap size, especially in a 32-bit architecture.

By closely combining the runtime and network libraries, fewer context switches are required for network operations.

Changes in the standard library

Bufio.Scanner

There are several ways to get text input in the bufio package, ReadBytes, ReadString, and special ReadLine, all of which are a bit too complex for simple purposes. In Go 1.1, a new type, Scanner, has been added to make it easier to handle simple tasks such as reading input sequences or space-delimited words by line. It terminates input errors such as typing a long problematic line and provides a simple default behavior: based on line input, delimited identifiers are removed for each line. The code here shows entering 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 the SplitFunc documentation), but for complex problems or constantly passing errors, the original interface may still be required.

Net

The network name passed in is lenient before the protocol-specific parser in the net package. Although the documentation makes it clear that only "tcp", "tcp4" and "tcp6" are legal network names for ResolveTCPAddr, the implementation of Go 1.0 will accept any string. The implementation of Go 1.1 returns an error if the network name is not in these strings. The same is true for other protocol-specific parsers ResolveIPAddr, ResolveUDPAddr, and ResolveUnixAddr.

In the previous implementation, ListenUnixgram returned a UDPConn as the endpoint of the receive connection. In the implementation of Go 1.1, UnixConn is used instead, which allows reading and writing with its ReadFrom and WriteTo methods.

The data structures IPAddr, TCPAddr, and UDPAddr add a new string field called Zone. Because of the new field, replacing the tagged grammar (net.TCPAddr {IP: ip, Port: port}) with the code of the untagged compound grammar (for example, net.TCPAddr {ip, port}) can cause an error. The compatibility rules of Go 1 allow this change: client code must use tagged grammars to avoid this damage.

Update: to fix the damage caused by the new structure field, go fix will rewrite these types of code to add tags. More generally, go vet will identify all composite grammars that should use field labels.

Reflect

The reflect package has several major 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 functional way to perform Go conversion and type assertion operations on a Value (or to detect this possibility).

The new function MakeFunc creates a wrapper function that makes it easier to invoke functions in existing Value, which can be used to convert standard Go parameters, such as passing an int to interface {}.

*, the new functions ChanOf, MapOf, and SliceOf can construct a new Type from an existing type, such as [] T when only T is provided.

Time

Previous time packages are accurate to microseconds on FreeBSD, Linux, NetBSD, OS X, and OpenBSD. The implementation of Go 1.1 on these operating systems can be accurate to nanoseconds. The program uses subtle accuracy to write and read out externally. If the original value is overwritten, it will result in a loss of accuracy. Time has two new methods, Round and Truncate, which can be used to remove precision from time before writing to external storage.

The new method YearDay returns the unique integer ordinal of the specified time value on a certain day of the year.

The Timer type has a new method, Reset, that makes the timer expire after the specified interval.

* A new function ParseInLocation is similar to the existing Parse, but ignores the time zone information in the parsed string and uses the passed location (time zone) to parse the time. This function solves the common confusion in time API.

Update: for code that uses a lower-precision external format to read and write time, it should be modified with a new method.

Exp's old code tree is moved to go.exp and go.text child version libraries

To make it easier for users using binary distributions to access when needed, exp that is not included in the binary distribution and the old source tree are moved to the new subversion library code.google.com/p/go.exp. For example, if you want to access the ssa package, execute

$go get code.google.com/p/go.exp/ssa

And then in the Go code

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

The old package exp/norm has also been migrated to the new version library go.text, which contains the Unicode API and other text-related packages under development.

Minor changes to the library

The following listing lists minor changes to the library, most of them enhancements. Refer to the documentation related to the package for more information about each change.

The bytes package has two new functions, TrimPrefix and TrimSuffix, which are self-evident. Similarly, the Buffer type has a new method, Grow, which provides some ability to control the internal memory allocation of the cache. * *, 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 MAC.

The crypto/x509 package now supports PEM blocks (see DecryptPEMBlock for an example), as well as a new function, ParseECPrivateKey, to parse the elliptic curve private key.

The database/sql package has a new Ping method on the DB type to detect the health of the connection.

Database/sql/driver has a new Queryer interface so that Conn can make some performance improvements by implementing it.

The Decoder of the encoding/json package has a new method Buffered to provide access to the remaining data in its cache, and the new method UseNumber decodes a value into a new type Number that is actually a string rather than a float64.

The encoding/xml package has a new function EscapeText, and the method Inden for outputting escape-passed XML,Encoder is dedicated to outputting indented formats.

In the go/ast package, the new type CommentMap and its associated methods make it easier to separate and process annotations from Go programs.

In the go/doc package, the parser can now better track identities such as TODO, and the godoc command can choose to filter or render this information based on the-notes parameter.

A new package, go/format, provides a more convenient way for programs to acquire the formatting capabilities of gofmt. It has two functions, Node to format Go's parsed Node and Source to format Go's source code.

The "noescape" feature, which is undocumented and only partially implemented in the html/template package, is removed; programs that depend on it are broken.

The io package now exports the io.ByteWriter interface for common functions such as writing one byte at a time.

The log/syslog package now provides better system-specific logging capabilities.

The Int type of the math/big package now has methods MarshalJSON and UnmarshalJSON to convert to or from JSON format. Similarly, Int can now be converted directly to uint64 or from uint64 through Uint64 and SetUint64, while Rat can now be converted through Float64 and SetFloat64.

The Writer of the mime/multipart package has a new method, and SetBoundary is used to define the boundary separation of the package output.

The ListenUnixgram function of the net package changed the type of return value: it now returns UnixConn instead of UDPConn, which is obviously an error of Go 1.0. So the change to API fixes a bug, which conforms to the compatibility rules of Go 1.

The net package contains a new function, DialOpt, which adds options to Dial. Each option is represented by the new interface DialOption. The new functions Deadline, Timeout, Network, and LocalAddress will certainly 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 the region information in a new field, and functions that require a string format as the address, such as Dial, ResolveIPAddr, ResolveUDPAddr, and ResolveTCPAddr, now accept the format with region validation.

The net package adds LookupNS as a parsing function. LookupNS returns a NS records based on the hostname.

The net package adds specified protocol read and write methods 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 of a packet.

Net adds methods to UnixConn to half-close the connection (CloseRead and CloseWrite), which matches the existing methods of TCPConn.

The net/http package contains several additions. ParseTime parses a time string and tries several common HTTP time formats. The PostFormValue method of Request is similar to FormValue, except that the URL parameter is ignored. The CloseNotifier interface provides a mechanism for server-side processors to discover that clients are disconnected. The ServeMux type now has a Handler method to access the path of the Handler without executing it. Transport can now cancel a request in progress through CancelRequest. * Transport will now be more optimistic about shutting down TCP connections when Response.Body is shut down before it is fully processed.

The new net/http/cookiejar package provides basic functionality for managing HTTP cookie.

The net/mail package has two new functions, ParseAddress and ParseAddressList, to resolve the RFC 5322 formatted address to the Address structure.

The Client type of the net/smtp package has a new method, Hello, to send HELO or EHLO messages to the server.

Net/textproto has two new functions, TrimBytes and TrimString, which are used to remove leading and trailing spaces only under ASCII.

The new method os.FileMode.IsRegular makes it easier to know whether a file is a normal file or not.

Image/jpeg can now read preloaded JPEG files and process some secondary sampling configuration information.

The regexp package now supports Unix native leftmost and longest matches through Regexp.Longest, while Regexp.Split uses a splitter defined by regular expressions to break strings into groups.

Runtime/debug has three new functions for memory usage. The FreeOSMemory function triggers garbage collection and attempts to return unused memory to the operating system; ReadGCStats obtains controller statistics; and SetGCPercent provides a programmable way to control the frequency of controller execution, including permanently disabling it.

The sort package has a new function, Reverse. As a package of parameters to call sort.Sort, you can reverse the sort results by calling Reverse.

The strings package has two new functions, TrimPrefix and TrimSuffix, which are self-evident, and the Reader.WriteTo method, so Reader now implements the io.WriterTo interface.

There are many updates to the syscall package, including hardening of system calls for each supported operating system.

The testing package can now automatically generate memory allocation statistics in performance tests using the AllocsPerRun function and BenchmarkResult's AllocsPerOp method. There is also the Verbose function to detect the command-line argument status of-v, and testing.B and testing.T 's new method Skip to simply skip some unnecessary tests.

In the text/template and html/template packages, templates can now group character sequences in parentheses, 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 ways to provide better error reporting. This also follows the Go 1 compatibility rules, and since this interface is explicitly expected to be used only by 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 code value. To ensure legality, the value of the rune must be within the range and cannot be half a substitute.

The implementation of the unicode package is updated to Unicode version 7.2.0.

Thank you for reading, the above is the content of "what are the new features of Go 1.1". After the study of this article, I believe you have a deeper understanding of the new features of Go 1.1, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report