1
0
mirror of https://github.com/golang/go synced 2024-11-21 20:34:40 -07:00

effective_go: a little more about comma ok and type assertion

Fixes #2416.

R=golang-dev, iant
CC=golang-dev
https://golang.org/cl/5370049
This commit is contained in:
Rob Pike 2011-11-09 16:14:18 -08:00
parent e4eacf39e9
commit bb66164542
2 changed files with 24 additions and 0 deletions

View File

@ -2719,6 +2719,18 @@ for try := 0; try < 2; try++ {
}
</pre>
<p>
The second <code>if</code> statement here is idiomatic Go.
The type assertion <code>err.(*os.PathError)</code> is
checked with the "comma ok" idiom (mentioned <a href="#maps">earlier</a>
in the context of examining maps).
If the type assertion fails, <code>ok</code> will be false, and <code>e</code>
will be <code>nil</code>.
If it succeeds, <code>ok</code> will be true, which means the
error was of type <code>*os.PathError</code>, and then so is <code>e</code>,
which we can examine for more information about the error.
</p>
<h3 id="panic">Panic</h3>
<p>

View File

@ -2657,6 +2657,18 @@ for try := 0; try &lt; 2; try++ {
}
</pre>
<p>
The second <code>if</code> statement here is idiomatic Go.
The type assertion <code>err.(*os.PathError)</code> is
checked with the "comma ok" idiom (mentioned <a href="#maps">earlier</a>
in the context of examining maps).
If the type assertion fails, <code>ok</code> will be false, and <code>e</code>
will be <code>nil</code>.
If it succeeds, <code>ok</code> will be true, which means the
error was of type <code>*os.PathError</code>, and then so is <code>e</code>,
which we can examine for more information about the error.
</p>
<h3 id="panic">Panic</h3>
<p>