gopl-zh.github.com/ch2/ch2-03.html

442 lines
46 KiB
HTML
Raw Normal View History

<!DOCTYPE HTML>
<html lang="zh" class="sidebar-visible no-js light">
<head>
<!-- Book generated using mdBook -->
<meta charset="UTF-8">
<title>变量 - Go语言圣经</title>
<!-- Custom HTML head -->
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta name="description" content="&lt;The Go Programming Language&gt;中文版">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#ffffff" />
<link rel="icon" href="../favicon.svg">
<link rel="shortcut icon" href="../favicon.png">
<link rel="stylesheet" href="../css/variables.css">
<link rel="stylesheet" href="../css/general.css">
<link rel="stylesheet" href="../css/chrome.css">
<link rel="stylesheet" href="../css/print.css" media="print">
<!-- Fonts -->
<link rel="stylesheet" href="../FontAwesome/css/font-awesome.css">
<link rel="stylesheet" href="../fonts/fonts.css">
<!-- Highlight.js Stylesheets -->
<link rel="stylesheet" href="../highlight.css">
<link rel="stylesheet" href="../tomorrow-night.css">
<link rel="stylesheet" href="../ayu-highlight.css">
<!-- Custom theme stylesheets -->
<link rel="stylesheet" href="../style.css">
</head>
<body>
<!-- Provide site root to javascript -->
<script type="text/javascript">
var path_to_root = "../";
var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
</script>
<!-- Work around some values being stored in localStorage wrapped in quotes -->
<script type="text/javascript">
try {
var theme = localStorage.getItem('mdbook-theme');
var sidebar = localStorage.getItem('mdbook-sidebar');
if (theme.startsWith('"') && theme.endsWith('"')) {
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
}
if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
}
} catch (e) { }
</script>
<!-- Set the theme before any content is loaded, prevents flash -->
<script type="text/javascript">
var theme;
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
if (theme === null || theme === undefined) { theme = default_theme; }
var html = document.querySelector('html');
html.classList.remove('no-js')
html.classList.remove('light')
html.classList.add(theme);
html.classList.add('js');
</script>
<!-- Hide / unhide sidebar before it is displayed -->
<script type="text/javascript">
var html = document.querySelector('html');
var sidebar = 'hidden';
if (document.body.clientWidth >= 1080) {
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
sidebar = sidebar || 'visible';
}
html.classList.remove('sidebar-visible');
html.classList.add("sidebar-" + sidebar);
</script>
<nav id="sidebar" class="sidebar" aria-label="Table of contents">
<div class="sidebar-scrollbox">
<ol class="chapter"><li class="chapter-item expanded affix "><a href="../index.html">Go语言圣经</a></li><li class="chapter-item expanded affix "><a href="../preface.html">前言</a></li><li class="chapter-item expanded "><a href="../ch1/ch1.html"><strong aria-hidden="true">1.</strong> 入门</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../ch1/ch1-01.html"><strong aria-hidden="true">1.1.</strong> Hello, World</a></li><li class="chapter-item expanded "><a href="../ch1/ch1-02.html"><strong aria-hidden="true">1.2.</strong> 命令行参数</a></li><li class="chapter-item expanded "><a href="../ch1/ch1-03.html"><strong aria-hidden="true">1.3.</strong> 查找重复的行</a></li><li class="chapter-item expanded "><a href="../ch1/ch1-04.html"><strong aria-hidden="true">1.4.</strong> GIF动画</a></li><li class="chapter-item expanded "><a href="../ch1/ch1-05.html"><strong aria-hidden="true">1.5.</strong> 获取URL</a></li><li class="chapter-item expanded "><a href="../ch1/ch1-06.html"><strong aria-hidden="true">1.6.</strong> 并发获取多个URL</a></li><li class="chapter-item expanded "><a href="../ch1/ch1-07.html"><strong aria-hidden="true">1.7.</strong> Web服务</a></li><li class="chapter-item expanded "><a href="../ch1/ch1-08.html"><strong aria-hidden="true">1.8.</strong> 本章要点</a></li></ol></li><li class="chapter-item expanded "><a href="../ch2/ch2.html"><strong aria-hidden="true">2.</strong> 程序结构</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../ch2/ch2-01.html"><strong aria-hidden="true">2.1.</strong> 命名</a></li><li class="chapter-item expanded "><a href="../ch2/ch2-02.html"><strong aria-hidden="true">2.2.</strong> 声明</a></li><li class="chapter-item expanded "><a href="../ch2/ch2-03.html" class="active"><strong aria-hidden="true">2.3.</strong> 变量</a></li><li class="chapter-item expanded "><a href="../ch2/ch2-04.html"><strong aria-hidden="true">2.4.</strong> 赋值</a></li><li class="chapter-item expanded "><a href="../ch2/ch2-05.html"><strong aria-hidden="true">2.5.</strong> 类型</a></li><li class="chapter-item expanded "><a href="../ch2/ch2-06.html"><strong aria-hidden="true">2.6.</strong> 包和文件</a></li><li class="chapter-item expanded "><a href="../ch2/ch2-07.html"><strong aria-hidden="true">2.7.</strong> 作用域</a></li></ol></li><li class="chapter-item expanded "><a href="../ch3/ch3.html"><strong aria-hidden="true">3.</strong> 基础数据类型</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../ch3/ch3-01.html"><strong aria-hidden="true">3.1.</strong> 整型</a></li><li class="chapter-item expanded "><a href="../ch3/ch3-02.html"><strong aria-hidden="true">3.2.</strong> 浮点数</a></li><li class="chapter-item expanded "><a href="../ch3/ch3-03.html"><strong aria-hidden="true">3.3.</strong> 复数</a></li><li class="chapter-item expanded "><a href="../ch3/ch3-04.html"><strong aria-hidden="true">3.4.</strong> 布尔型</a></li><li class="chapter-item expanded "><a href="../ch3/ch3-05.html"><strong aria-hidden="true">3.5.</strong> 字符串</a></li><li class="chapter-item expanded "><a href="../ch3/ch3-06.html"><strong aria-hidden="true">3.6.</strong> 常量</a></li></ol></li><li class="chapter-item expanded "><a href="../ch4/ch4.html"><strong aria-hidden="true">4.</strong> 复合数据类型</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../ch4/ch4-01.html"><strong aria-hidden="true">4.1.</strong> 数组</a></li><li class="chapter-item expanded "><a href="../ch4/ch4-02.html"><strong aria-hidden="true">4.2.</strong> Slice</a></li><li class="chapter-item expanded "><a href="../ch4/ch4-03.html"><strong aria-hidden="true">4.3.</strong> Map</a></li><li class="chapter-item expanded "><a href="../ch4/ch4-04.html"><strong aria-hidden="true">4.4.</strong> 结构体</a></li><li class="chapter-item expanded "><a href="../ch4/ch4-05.html"><strong aria-hidden="true">4.5.</strong> JSON</a></li><li class="chapter-item expanded "><a href="../ch4/ch4-06.html"><s
<div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
</nav>
<div id="page-wrapper" class="page-wrapper">
<div class="page">
<div id="menu-bar-hover-placeholder"></div>
<div id="menu-bar" class="menu-bar sticky bordered">
<div class="left-buttons">
<button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
<i class="fa fa-bars"></i>
</button>
<button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
<i class="fa fa-paint-brush"></i>
</button>
<ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
<li role="none"><button role="menuitem" class="theme" id="light">Light (default)</button></li>
<li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
<li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
<li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
<li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
</ul>
<button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
<i class="fa fa-search"></i>
</button>
</div>
<h1 class="menu-title">Go语言圣经</h1>
<div class="right-buttons">
<a href="../print.html" title="Print this book" aria-label="Print this book">
<i id="print-button" class="fa fa-print"></i>
</a>
<a href="https://github.com/gopl-zh/gopl-zh.github.com" title="Git repository" aria-label="Git repository">
<i id="git-repository-button" class="fa fa-github"></i>
</a>
<a href="https://github.com/gopl-zh/gopl-zh.github.com/edit/master/./ch2/ch2-03.md" title="Suggest an edit" aria-label="Suggest an edit">
<i id="git-edit-button" class="fa fa-edit"></i>
</a>
</div>
</div>
<div id="search-wrapper" class="hidden">
<form id="searchbar-outer" class="searchbar-outer">
<input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
</form>
<div id="searchresults-outer" class="searchresults-outer hidden">
<div id="searchresults-header" class="searchresults-header"></div>
<ul id="searchresults">
</ul>
</div>
</div>
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
<script type="text/javascript">
document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
});
</script>
<div id="content" class="content">
<!-- Page table of contents -->
<div class="sidetoc"><nav class="pagetoc"></nav></div>
<main>
<!-- 头部 -->
<ul dir="auto">
<li><em>KusonStack一站式可编程配置技术栈(Go): <a href="https://github.com/KusionStack/kusion">https://github.com/KusionStack/kusion</a></em></li>
<li><em>KCL 配置编程语言(Rust): <a href="https://github.com/KusionStack/KCLVM">https://github.com/KusionStack/KCLVM</a></em></li>
<li><em>凹语言™: <a href="https://github.com/wa-lang/wa">https://github.com/wa-lang/wa</a></em></li>
</ul>
<hr>
<h2 id="23-变量"><a class="header" href="#23-变量">2.3. 变量</a></h2>
<p>var声明语句可以创建一个特定类型的变量然后给变量附加一个名字并且设置变量的初始值。变量声明的一般语法如下</p>
<pre><code class="language-Go">var 变量名字 类型 = 表达式
</code></pre>
<p>其中“<em>类型</em>”或“<em>= 表达式</em>”两个部分可以省略其中的一个。如果省略的是类型信息,那么将根据初始化表达式来推导变量的类型信息。如果初始化表达式被省略,那么将用零值初始化该变量。 数值类型变量对应的零值是0布尔类型变量对应的零值是false字符串类型对应的零值是空字符串接口或引用类型包括slice、指针、map、chan和函数变量对应的零值是nil。数组或结构体等聚合类型对应的零值是每个元素或字段都是对应该类型的零值。</p>
<p>零值初始化机制可以确保每个声明的变量总是有一个良好定义的值因此在Go语言中不存在未初始化的变量。这个特性可以简化很多代码而且可以在没有增加额外工作的前提下确保边界条件下的合理行为。例如</p>
<pre><code class="language-Go">var s string
fmt.Println(s) // &quot;&quot;
</code></pre>
<p>这段代码将打印一个空字符串而不是导致错误或产生不可预知的行为。Go语言程序员应该让一些聚合类型的零值也具有意义这样可以保证不管任何类型的变量总是有一个合理有效的零值状态。</p>
<p>也可以在一个声明语句中同时声明一组变量,或用一组初始化表达式声明并初始化一组变量。如果省略每个变量的类型,将可以声明多个类型不同的变量(类型由初始化表达式推导):</p>
<pre><code class="language-Go">var i, j, k int // int, int, int
var b, f, s = true, 2.3, &quot;four&quot; // bool, float64, string
</code></pre>
<p>初始化表达式可以是字面量或任意的表达式。在包级别声明的变量会在main入口函数执行前完成初始化§2.6.2),局部变量将在声明语句被执行到的时候完成初始化。</p>
<p>一组变量也可以通过调用一个函数,由函数返回的多个返回值初始化:</p>
<pre><code class="language-Go">var f, err = os.Open(name) // os.Open returns a file and an error
</code></pre>
<h3 id="231-简短变量声明"><a class="header" href="#231-简短变量声明">2.3.1. 简短变量声明</a></h3>
<p>在函数内部,有一种称为简短变量声明语句的形式可用于声明和初始化局部变量。它以“名字 := 表达式”形式声明变量变量的类型根据表达式来自动推导。下面是lissajous函数中的三个简短变量声明语句§1.4</p>
<pre><code class="language-Go">anim := gif.GIF{LoopCount: nframes}
freq := rand.Float64() * 3.0
t := 0.0
</code></pre>
<p>因为简洁和灵活的特点简短变量声明被广泛用于大部分的局部变量的声明和初始化。var形式的声明语句往往是用于需要显式指定变量类型的地方或者因为变量稍后会被重新赋值而初始值无关紧要的地方。</p>
<pre><code class="language-Go">i := 100 // an int
var boiling float64 = 100 // a float64
var names []string
var err error
var p Point
</code></pre>
<p>和var形式声明语句一样简短变量声明语句也可以用来声明和初始化一组变量</p>
<pre><code class="language-Go">i, j := 0, 1
</code></pre>
<p>但是这种同时声明多个变量的方式应该限制只在可以提高代码可读性的地方使用比如for语句的循环的初始化语句部分。</p>
<p>请记住“:=”是一个变量声明语句,而“=”是一个变量赋值操作。也不要混淆多个变量的声明和元组的多重赋值§2.4.1),后者是将右边各个表达式的值赋值给左边对应位置的各个变量:</p>
<pre><code class="language-Go">i, j = j, i // 交换 i 和 j 的值
</code></pre>
<p>和普通var形式的变量声明语句一样简短变量声明语句也可以用函数的返回值来声明和初始化变量像下面的os.Open函数调用将返回两个值</p>
<pre><code class="language-Go">f, err := os.Open(name)
if err != nil {
return err
}
// ...use f...
f.Close()
</code></pre>
<p>这里有一个比较微妙的地方简短变量声明左边的变量可能并不是全部都是刚刚声明的。如果有一些已经在相同的词法域声明过了§2.7),那么简短变量声明语句对这些已经声明过的变量就只有赋值行为了。</p>
<p>在下面的代码中第一个语句声明了in和err两个变量。在第二个语句只声明了out一个变量然后对已经声明的err进行了赋值操作。</p>
<pre><code class="language-Go">in, err := os.Open(infile)
// ...
out, err := os.Create(outfile)
</code></pre>
<p>简短变量声明语句中必须至少要声明一个新的变量,下面的代码将不能编译通过:</p>
<pre><code class="language-Go">f, err := os.Open(infile)
// ...
f, err := os.Create(outfile) // compile error: no new variables
</code></pre>
<p>解决的方法是第二个简短变量声明语句改用普通的多重赋值语句。</p>
<p>简短变量声明语句只有对已经在同级词法域声明过的变量才和赋值操作语句等价,如果变量是在外部词法域声明的,那么简短变量声明语句将会在当前词法域重新声明一个新的变量。我们在本章后面将会看到类似的例子。</p>
<h3 id="232-指针"><a class="header" href="#232-指针">2.3.2. 指针</a></h3>
<p>一个变量对应一个保存了变量对应类型值的内存空间。普通变量在声明语句创建时被绑定到一个变量名比如叫x的变量但是还有很多变量始终以表达式方式引入例如x[i]或x.f变量。所有这些表达式一般都是读取一个变量的值除非它们是出现在赋值语句的左边这种时候是给对应变量赋予一个新的值。</p>
<p>一个指针的值是另一个变量的地址。一个指针对应变量在内存中的存储位置。并不是每一个值都会有一个内存地址,但是对于每一个变量必然有对应的内存地址。通过指针,我们可以直接读或更新对应变量的值,而不需要知道该变量的名字(如果变量有名字的话)。</p>
<p>如果用“var x int”声明语句声明一个x变量那么&amp;x表达式取x变量的内存地址将产生一个指向该整数变量的指针指针对应的数据类型是<code>*int</code>指针被称之为“指向int类型的指针”。如果指针名字为p那么可以说“p指针指向变量x”或者说“p指针保存了x变量的内存地址”。同时<code>*p</code>表达式对应p指针指向的变量的值。一般<code>*p</code>表达式读取指针指向的变量的值这里为int类型的值同时因为<code>*p</code>对应一个变量,所以该表达式也可以出现在赋值语句的左边,表示更新指针所指向的变量的值。</p>
<pre><code class="language-Go">x := 1
p := &amp;x // p, of type *int, points to x
fmt.Println(*p) // &quot;1&quot;
*p = 2 // equivalent to x = 2
fmt.Println(x) // &quot;2&quot;
</code></pre>
<p>对于聚合类型每个成员——比如结构体的每个字段、或者是数组的每个元素——也都是对应一个变量,因此可以被取地址。</p>
<p>变量有时候被称为可寻址的值。即使变量由表达式临时生成,那么表达式也必须能接受<code>&amp;</code>取地址操作。</p>
<p>任何类型的指针的零值都是nil。如果p指向某个有效变量那么<code>p != nil</code>测试为真。指针之间也是可以进行相等测试的只有当它们指向同一个变量或全部是nil时才相等。</p>
<pre><code class="language-Go">var x, y int
fmt.Println(&amp;x == &amp;x, &amp;x == &amp;y, &amp;x == nil) // &quot;true false false&quot;
</code></pre>
<p>在Go语言中返回函数中局部变量的地址也是安全的。例如下面的代码调用f函数时创建局部变量v在局部变量地址被返回之后依然有效因为指针p依然引用这个变量。</p>
<pre><code class="language-Go">var p = f()
func f() *int {
v := 1
return &amp;v
}
</code></pre>
<p>每次调用f函数都将返回不同的结果</p>
<pre><code class="language-Go">fmt.Println(f() == f()) // &quot;false&quot;
</code></pre>
<p>因为指针包含了一个变量的地址因此如果将指针作为参数调用函数那将可以在函数中通过该指针来更新变量的值。例如下面这个例子就是通过指针来更新变量的值然后返回更新后的值可用在一个表达式中译注这是对C语言中<code>++v</code>操作的模拟这里只是为了说明指针的用法incr函数模拟的做法并不推荐</p>
<pre><code class="language-Go">func incr(p *int) int {
*p++ // 非常重要只是增加p指向的变量的值并不改变p指针
return *p
}
v := 1
incr(&amp;v) // side effect: v is now 2
fmt.Println(incr(&amp;v)) // &quot;3&quot; (and v is 3)
</code></pre>
<p>每次我们对一个变量取地址,或者复制指针,我们都是为原变量创建了新的别名。例如,<code>*p</code>就是变量v的别名。指针特别有价值的地方在于我们可以不用名字而访问一个变量但是这是一把双刃剑要找到一个变量的所有访问者并不容易我们必须知道变量全部的别名译注这是Go语言的垃圾回收器所做的工作。不仅仅是指针会创建别名很多其他引用类型也会创建别名例如slice、map和chan甚至结构体、数组和接口都会创建所引用变量的别名。</p>
<p>指针是实现标准库中flag包的关键技术它使用命令行参数来设置对应变量的值而这些对应命令行标志参数的变量可能会零散分布在整个程序中。为了说明这一点在早些的echo版本中就包含了两个可选的命令行参数<code>-n</code>用于忽略行尾的换行符,<code>-s sep</code>用于指定分隔字符默认是空格。下面这是第四个版本对应包路径为gopl.io/ch2/echo4。</p>
<p><u><i>gopl.io/ch2/echo4</i></u></p>
<pre><code class="language-Go">// Echo4 prints its command-line arguments.
package main
import (
&quot;flag&quot;
&quot;fmt&quot;
&quot;strings&quot;
)
var n = flag.Bool(&quot;n&quot;, false, &quot;omit trailing newline&quot;)
var sep = flag.String(&quot;s&quot;, &quot; &quot;, &quot;separator&quot;)
func main() {
flag.Parse()
fmt.Print(strings.Join(flag.Args(), *sep))
if !*n {
fmt.Println()
}
}
</code></pre>
<p>调用flag.Bool函数会创建一个新的对应布尔型标志参数的变量。它有三个属性第一个是命令行标志参数的名字“n”然后是该标志参数的默认值这里是false最后是该标志参数对应的描述信息。如果用户在命令行输入了一个无效的标志参数或者输入<code>-h</code><code>-help</code>参数那么将打印所有标志参数的名字、默认值和描述信息。类似的调用flag.String函数将创建一个对应字符串类型的标志参数变量同样包含命令行标志参数对应的参数名、默认值、和描述信息。程序中的<code>sep</code><code>n</code>变量分别是指向对应命令行标志参数变量的指针,因此必须用<code>*sep</code><code>*n</code>形式的指针语法间接引用它们。</p>
<p>当程序运行时必须在使用标志参数对应的变量之前先调用flag.Parse函数用于更新每个标志参数对应变量的值之前是默认值。对于非标志参数的普通命令行参数可以通过调用flag.Args()函数来访问返回值对应一个字符串类型的slice。如果在flag.Parse函数解析命令行参数时遇到错误默认将打印相关的提示信息然后调用os.Exit(2)终止程序。</p>
<p>让我们运行一些echo测试用例</p>
<pre><code>$ go build gopl.io/ch2/echo4
$ ./echo4 a bc def
a bc def
$ ./echo4 -s / a bc def
a/bc/def
$ ./echo4 -n a bc def
a bc def$
$ ./echo4 -help
Usage of ./echo4:
-n omit trailing newline
-s string
separator (default &quot; &quot;)
</code></pre>
<h3 id="233-new函数"><a class="header" href="#233-new函数">2.3.3. new函数</a></h3>
<p>另一个创建变量的方法是调用内建的new函数。表达式new(T)将创建一个T类型的匿名变量初始化为T类型的零值然后返回变量地址返回的指针类型为<code>*T</code></p>
<pre><code class="language-Go">p := new(int) // p, *int 类型, 指向匿名的 int 变量
fmt.Println(*p) // &quot;0&quot;
*p = 2 // 设置 int 匿名变量的值为 2
fmt.Println(*p) // &quot;2&quot;
</code></pre>
<p>用new创建变量和普通变量声明语句方式创建变量没有什么区别除了不需要声明一个临时变量的名字外我们还可以在表达式中使用new(T)。换言之new函数类似是一种语法糖而不是一个新的基础概念。</p>
<p>下面的两个newInt函数有着相同的行为</p>
<pre><code class="language-Go">func newInt() *int {
return new(int)
}
func newInt() *int {
var dummy int
return &amp;dummy
}
</code></pre>
<p>每次调用new函数都是返回一个新的变量的地址因此下面两个地址是不同的</p>
<pre><code class="language-Go">p := new(int)
q := new(int)
fmt.Println(p == q) // &quot;false&quot;
</code></pre>
<p>当然也可能有特殊情况如果两个类型都是空的也就是说类型的大小是0例如<code>struct{}</code><code>[0]int</code>有可能有相同的地址依赖具体的语言实现译注请谨慎使用大小为0的类型因为如果类型的大小为0的话可能导致Go语言的自动垃圾回收器有不同的行为具体请查看<code>runtime.SetFinalizer</code>函数相关文档)。</p>
<p>new函数使用通常相对比较少因为对于结构体来说直接用字面量语法创建新变量的方法会更灵活§4.4.1)。</p>
<p>由于new只是一个预定义的函数它并不是一个关键字因此我们可以将new名字重新定义为别的类型。例如下面的例子</p>
<pre><code class="language-Go">func delta(old, new int) int { return new - old }
</code></pre>
<p>由于new被定义为int类型的变量名因此在delta函数内部是无法使用内置的new函数的。</p>
<h3 id="234-变量的生命周期"><a class="header" href="#234-变量的生命周期">2.3.4. 变量的生命周期</a></h3>
<p>变量的生命周期指的是在程序运行期间变量有效存在的时间段。对于在包一级声明的变量来说,它们的生命周期和整个程序的运行周期是一致的。而相比之下,局部变量的生命周期则是动态的:每次从创建一个新变量的声明语句开始,直到该变量不再被引用为止,然后变量的存储空间可能被回收。函数的参数变量和返回值变量都是局部变量。它们在函数每次被调用的时候创建。</p>
<p>例如下面是从1.4节的Lissajous程序摘录的代码片段</p>
<pre><code class="language-Go">for t := 0.0; t &lt; cycles*2*math.Pi; t += res {
x := math.Sin(t)
y := math.Sin(t*freq + phase)
img.SetColorIndex(size+int(x*size+0.5), size+int(y*size+0.5),
blackIndex)
}
</code></pre>
<p>译注:函数的右小括弧也可以另起一行缩进,同时为了防止编译器在行尾自动插入分号而导致的编译错误,可以在末尾的参数变量后面显式插入逗号。像下面这样:</p>
<pre><code class="language-Go">for t := 0.0; t &lt; cycles*2*math.Pi; t += res {
x := math.Sin(t)
y := math.Sin(t*freq + phase)
img.SetColorIndex(
size+int(x*size+0.5), size+int(y*size+0.5),
blackIndex, // 最后插入的逗号不会导致编译错误这是Go编译器的一个特性
) // 小括弧另起一行缩进,和大括弧的风格保存一致
}
</code></pre>
<p>在每次循环的开始会创建临时变量t然后在每次循环迭代中创建临时变量x和y。</p>
<p>那么Go语言的自动垃圾收集器是如何知道一个变量是何时可以被回收的呢这里我们可以避开完整的技术细节基本的实现思路是从每个包级的变量和每个当前运行函数的每一个局部变量开始通过指针或引用的访问路径遍历是否可以找到该变量。如果不存在这样的访问路径那么说明该变量是不可达的也就是说它是否存在并不会影响程序后续的计算结果。</p>
<p>因为一个变量的有效周期只取决于是否可达,因此一个循环迭代内部的局部变量的生命周期可能超出其局部作用域。同时,局部变量可能在函数返回之后依然存在。</p>
<p>编译器会自动选择在栈上还是在堆上分配局部变量的存储空间但可能令人惊讶的是这个选择并不是由用var还是new声明变量的方式决定的。</p>
<pre><code class="language-Go">var global *int
func f() {
var x int
x = 1
global = &amp;x
}
func g() {
y := new(int)
*y = 1
}
</code></pre>
<p>f函数里的x变量必须在堆上分配因为它在函数退出后依然可以通过包一级的global变量找到虽然它是在函数内部定义的用Go语言的术语说这个x局部变量从函数f中逃逸了。相反当g函数返回时变量<code>*y</code>将是不可达的,也就是说可以马上被回收的。因此,<code>*y</code>并没有从函数g中逃逸编译器可以选择在栈上分配<code>*y</code>的存储空间译注也可以选择在堆上分配然后由Go语言的GC回收这个变量的内存空间虽然这里用的是new方式。其实在任何时候你并不需为了编写正确的代码而要考虑变量的逃逸行为要记住的是逃逸的变量需要额外分配内存同时对性能的优化可能会产生细微的影响。</p>
<p>Go语言的自动垃圾收集器对编写正确的代码是一个巨大的帮助但也并不是说你完全不用考虑内存了。你虽然不需要显式地分配和释放内存但是要编写高效的程序你依然需要了解变量的生命周期。例如如果将指向短生命周期对象的指针保存到具有长生命周期的对象中特别是保存到全局变量时会阻止对短生命周期对象的垃圾回收从而可能影响程序的性能</p>
<!-- 公众号 -->
<hr>
<table>
<tr>
<td>
<img width="222px" src="https://chai2010.cn/advanced-go-programming-book/css.png">
</td>
<td>
<img width="222px" src="https://chai2010.cn/advanced-go-programming-book/cch.png">
</td>
</tr>
</table>
<div id="giscus-container"></div>
<footer class="page-footer">
<span>© 2015-2016 | <a href="https://github.com/gopl-zh"> Go语言圣经中文版</a>, 仅学习交流使用</span>
</footer>
</main>
<nav class="nav-wrapper" aria-label="Page navigation">
<!-- Mobile navigation buttons -->
<a rel="prev" href="../ch2/ch2-02.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
<a rel="next" href="../ch2/ch2-04.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<i class="fa fa-angle-right"></i>
</a>
<div style="clear: both"></div>
</nav>
</div>
</div>
<nav class="nav-wide-wrapper" aria-label="Page navigation">
<a rel="prev" href="../ch2/ch2-02.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
<a rel="next" href="../ch2/ch2-04.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<i class="fa fa-angle-right"></i>
</a>
</nav>
</div>
<script type="text/javascript">
window.playground_copyable = true;
</script>
<script src="../elasticlunr.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../mark.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../searcher.js" type="text/javascript" charset="utf-8"></script>
<script src="../clipboard.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../highlight.js" type="text/javascript" charset="utf-8"></script>
<script src="../book.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
var pagePath = "ch2/ch2-03.md"
</script>
<!-- Custom JS scripts -->
<script type="text/javascript" src="../js/custom.js"></script>
<script type="text/javascript" src="../js/bigPicture.js"></script>
</body>
</html>