当前位置:   article > 正文

golang ..._您需要了解的Go版本1.11

golang 1.11

golang ...

by Ridham Tarpara

由里德姆·塔帕拉(Ridham Tarpara)

您需要了解的Go版本1.11 (All you need to know about Go version 1.11)

Go 1.11 hit the ground on 24 August 2018. It introduces a few really needed tools and components such as versioned modules, WebAssembly support, and debugging improvements. It also brings some changes to core packages and performance/run-time.

Go 1.11于2018年8月24日投入使用。它引入了一些真正需要的工具和组件,例如版本模块,WebAssembly支持和调试改进。 它还对核心软件包和性能/运行时间进行了一些更改。

As always, the release maintains the Go 1 promise of compatibility. So almost all Go programs continue to compile and run as before with this update. There are no changes to the language specification.

与往常一样,该发行版保留了Go 1 兼容性的承诺 。 因此,几乎所有Go程序都继续像以前一样通过此更新进行编译和运行。 语言规范没有变化。

Let’s take a look at what’s new.

让我们看一下新功能。

模组 (Modules)

Go 1.11 includes experimental support for Go modules, including a new module-aware go get command.

Go 1.11包括对Go模块的实验性支持,其中包括一个新的可识别模块的go get命令。

The quickest way to take advantage of the new module support is to check out your repository into a directory outside, create a go.mod file and run Go commands from within that file tree.

充分利用新模块支持的最快方法是将存储库检出到外部目录中创建go.mod文件,然后从该文件树中运行Go命令。

Let’s demo this. I am using the testify-powerful and standard Go testing libraries.

让我们演示一下。 我正在使用功能强大testify和标准的Go测试库

Let’s clone the testify repo in my favorite folder ~/proj/github .

让我们在我最喜欢的文件夹~/proj/github克隆~/proj/github

$ git clone https://github.com/stretchr/testify ~/proj/github/testify$ cd ~/proj/github/testify

Now, to use Go commands from here, you need to initialize this repo as a module with the following command:

现在,要从此处使用Go命令,您需要使用以下命令将此仓库初始化为模块:

go mod init github.com/stretchr/testify

Where github.com/stretchr/testify is the location you would generally put this repo, under the Go src folder.

github.com/stretchr/testify是您通常将此存储库放置在Go src文件夹下的位置。

This command will create a go.mod file in the root of the folder. In a project already using an existing dependency management tool like godep, glide, or dep, go mod init will also add require statements matching the existing configuration.

此命令将在文件夹的根目录中创建一个go.mod文件。 在已经使用现有的依赖管理工具(例如godep,glide或dep)的项目中, go mod init还将添加与现有配置匹配的require语句。

Now if you open the go.mod file, you can see the list of dependencies with the module name.

现在,如果您打开go.mod文件,您将看到带有模块名称的依赖项列表。

$ vi go.mod
module github.com/stretchr/testify
require (    github.com/davecgh/go-spew v1.1.0    github.com/pmezard/go-difflib v1.0.0    github.com/stretchr/objx v0.1.0)

As you’ll notice, these three are the dependencies of the testify. This is testify’s Gopkg.toml file:

您会注意到,这三个是testify的依赖项。 这是作证的Gopkg.toml文件:

[prune] unused-packages = true non-go = true go-tests = true
[[constraint]] name = “github.com/davecgh/go-spew” version = “~1.1.0
[[constraint]] name = “github.com/pmezard/go-difflib” version = “~1.0.0
[[constraint]] name = “github.com/stretchr/objx” version = “~0.1.0

Now that the module has been initialized, you can use any Go command from this folder.

现在已经初始化了模块,您可以使用此文件夹中的任何Go命令。

╭─ ~/proj/github/testify  ‹master*› ╰─$ go build                               go: finding github.com/davecgh/go-spew v1.1.0go: finding github.com/pmezard/go-difflib v1.0.0go: finding github.com/stretchr/objx v0.1.0go: downloading github.com/davecgh/go-spew v1.1.0go: downloading github.com/pmezard/go-difflib v1.0.0go: downloading github.com/stretchr/objx v0.1.0
╭─ ~/proj/github/testify  ‹master*› ╰─$ go test PASSok   github.com/stretchr/testify 0.001s

So with Go 1.11 and modules, you can write your Go modules anywhere you like and you don’t need to maintain a copy in a specific sub directory of your $GOPATH.

因此,使用Go 1.11和模块,您可以在任意位置编写Go模块,而无需在其中维护副本 $GOPATH的特定子目录。

Web组装 (WebAssembly)

Go 1.11 adds an experimental port to WebAssembly.

Go 1.11向WebAssembly添加了一个实验端口。

WebAssembly (abbreviated Wasm) is a binary instruction format for a stack-based virtual machine. Wasm is designed as a portable target for compilation of high-level languages like C/C++/Rust, enabling deployment on the web for client and server applications.

WebAssembly(缩写为Wasm )是基于堆栈的虚拟机的二进制指令格式。 Wasm被设计为可移植目标,用于编译高级语言(如C / C ++ / Rust),从而可以在Web上为客户端和服务器应用程序进行部署。

Now we can run Go in the browser, and vice versa — we can run JavaScript in Go easily. Although this feature is in the experimental state, it’s still pretty useful.

现在,我们可以在浏览器中运行Go,反之亦然-我们可以轻松地在Go中运行JavaScript。 尽管此功能处于实验状态,但仍然非常有用。

This small example calls Go from the Web:

这个小示例从Web调用Go:

wasm-exec.html

wasm-exec.html

<!doctype html><!--Copyright 2018 The Go Authors. All rights reserved.Use of this source code is governed by a BSD-stylelicense that can be found in the LICENSE file.--><html>
<head>    <meta charset="utf-8">    <title>Go wasm</title></head>
<body>    <script src="wasm_exec.js"></script>    <script>        if (!WebAssembly.instantiateStreaming) { // polyfill            WebAssembly.instantiateStreaming = async (resp, importObject) => {                const source = await (await resp).arrayBuffer();                return await WebAssembly.instantiate(source, importObject);            };        }        const go = new Go();        let mod, inst;        WebAssembly.instantiateStreaming(fetch("test.wasm"), go.importObject).then((result) => {            mod = result.module;            inst = result.instance;            document.getElementById("runButton").disabled = false;        });        let printMessage // Our reference to the Go callback        let printMessageReceived // Our promise        let resolvePrintMessageReceived // Our promise resolver        function setPrintMessage(callback) {          printMessage = callback          resolvePrintMessageReceived()        }        async function run() {          console.clear()          // Create the Promise and store its resolve function          printMessageReceived = new Promise(resolve => {            resolvePrintMessageReceived = resolve          })          const run = go.run(inst) // Start the wasm binary          await printMessageReceived // Wait for the callback reception          printMessage('Hello Wasm!') // Invoke the callback          await run // Wait for the binary to terminate          inst = await WebAssembly.instantiate(mod, go.importObject) // reset instance        }    </script>
<button onClick="run();" id="runButton" disabled>Run</button></body>
</html>

go-call.go

go-call.go

package main
import (  "fmt"  "syscall/js")
var done = make(chan struct{})
func main() {  callback := js.NewCallback(printMessage)  defer callback.Release() // To defer the callback releasing is a good practice  setPrintMessage := js.Global().Get("setPrintMessage")  setPrintMessage.Invoke(callback)  <-done}
func printMessage(args []js.Value) {  message := args[0].String()  fmt.Println(message)  done <- struct{}{} // Notify printMessage has been called}

You can find more examples here. And here is a video on building a calculator with WebAssembly.

您可以在此处找到更多示例。 这是有关使用WebAssembly构建计算器的视频。

其他需要考虑的变化 (Other changes to consider)

  • Because Go module support assigns special meaning to the @ symbol in command line operations, the gocommand now disallows the use of import paths containing @ symbols.

    由于Go模块支持在命令行操作中为@符号分配了特殊含义,因此go命令现在禁止使用包含@符号的导入路径。

  • With the new runtime/trace package's user annotation API, users can record application-level information in execution traces and create groups of related goroutines. The go tool trace command visualizes this information in the trace view and the new user task/region analysis page.

    使用新的runtime/trace包的用户注释API ,用户可以在执行跟踪中记录应用程序级别的信息,并创建相关的goroutine组。 go tool trace命令可以在跟踪视图和新的用户任务/区域分析页面中可视化此信息。

  • The runtime now uses a sparse heap layout so there is no longer a limit to the size of the Go heap (previously, the limit was 512GiB). This also fixes rare “address space conflict” failures in mixed Go/C binaries or binaries compiled with -race.

    现在,运行时使用的是稀疏堆布局,因此Go堆的大小不再受限制(以前,限制为512GiB)。 这还修复了混合Go / C二进制文件或使用-race编译的二进制文件中罕见的“地址空间冲突”故障。

  • time: Parsing of timezones denoted by sign and offset is now supported. In previous versions, numeric timezone names (such as +03) were not considered valid, and only three-letter abbreviations (such as MST) were accepted when expecting a timezone name.

    time :现在支持解析由符号和偏移量表示的时区。 在以前的版本中,数字时区名称(例如+03 )被认为无效,并且在期望时区名称时仅接受三个字母的缩写(例如MST )。

  • text/scanner: The Scanner.Scan method now returns the RawString token instead of String for raw string literals.

    text / scannerScanner.Scan方法现在针对原始字符串文字返回RawString令牌而不是String

  • There are changes in crypto, encoding, net/http, os, runtime, sync, mime and few others which you can read about here.

    加密编码net / httpos运行时同步mime以及其他一些变化都可以在这里阅读。

If you enjoyed this article, spare me some claps — it means the world to the writer. Follow me if you want to read more articles about Go, JavaScript, Technology, and Startups.

如果您喜欢这篇文章,请给我鼓掌-这对作家来说意味着世界。 如果您想阅读有关Go,JavaScript,技术和启动的更多文章,请关注我。

翻译自: https://www.freecodecamp.org/news/all-you-need-to-know-about-go-1-11-webassembly-modules-and-major-changes-df6a02108373/

golang ...

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/神奇cpp/article/detail/974789
推荐阅读
  

闽ICP备14008679号