<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Objectzilla &#187; go lang</title>
	<atom:link href="http://www.objectzilla.com.br/tag/go-lang/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.objectzilla.com.br</link>
	<description>por Leonardo Veríssimo</description>
	<lastBuildDate>Sat, 05 Jun 2010 18:58:50 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Go With the Flow</title>
		<link>http://www.objectzilla.com.br/2009/11/21/go-with-the-flow/</link>
		<comments>http://www.objectzilla.com.br/2009/11/21/go-with-the-flow/#comments</comments>
		<pubDate>Sat, 21 Nov 2009 23:57:34 +0000</pubDate>
		<dc:creator>Leonardo</dc:creator>
				<category><![CDATA[Sem categoria]]></category>
		<category><![CDATA[go]]></category>
		<category><![CDATA[go lang]]></category>
		<category><![CDATA[objetos]]></category>
		<category><![CDATA[paralelismo]]></category>

		<guid isPermaLink="false">http://www.objectzilla.com.br/?p=268</guid>
		<description><![CDATA[A Google tem um poderoso canal de comunicação com os nerds de todo o planeta. Tudo que sai da cabeça desses engenheiros é motivo de burburinho em todo o lugar, até que desapareça tempos depois.
A mais recente invenção dos caras é a GO, uma linguagem de programação de sistemas, compilável, com coletor de lixo e [...]]]></description>
			<content:encoded><![CDATA[<p>A Google tem um poderoso canal de comunicação com os nerds de todo o planeta. Tudo que sai da cabeça desses engenheiros é motivo de burburinho em todo o lugar, até que desapareça tempos depois.</p>
<p>A mais recente invenção dos caras é a <a href="http://golang.org/">GO</a>, uma linguagem de programação de sistemas, compilável, com coletor de lixo e primitivas para concorrência. Em poucos dias, causou vários comentários que, obviamente, se arrefeceram uma semana depois. Mas não vamos deixar essa ausência de comentários abalar este post onde, com apenas meus poucos dias de estudo, mostrarei meus pitacos com relações a aspectos da linguagem que mais se destacam dos demais. (Não mostrarei como montar o ambiente, nem como fazer compilação. Isso você encontra no Google.)<span id="more-268"></span></p>
<h1>Sintaxe</h1>
<p>A sintaxe é ligeiramente igual às famílias da linguagem C (como Java, C++ ou C#), com a diferença que os tipos vem depois do nome da variável ou da função. Um exemplo:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">package main
&nbsp;
import <span style="color: #ff0000;">&quot;fmt&quot;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// constante, tipo é implícito</span>
<span style="color: #993333;">const</span> Pi <span style="color: #339933;">=</span> <span style="color:#800080;">3.1415</span>
&nbsp;
<span style="color: #808080; font-style: italic;">/* 
Métodos começam com &quot;func&quot;, seguido do nome,
dos parâmetros e depois o retorno.
No parâmetro, tipo &quot;int&quot; vem depois no nome &quot;v&quot;
*/</span>
func doubleIt<span style="color: #009900;">&#40;</span>v <span style="color: #993333;">int</span><span style="color: #009900;">&#41;</span> <span style="color: #993333;">int</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #b1b100;">return</span> v <span style="color: #339933;">*</span> <span style="color: #0000dd;">2</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// o começo de um programa é o método main do pacote main</span>
func main<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #666666; font-style: italic;">// variáveis começam com var, seguido de nome e tipo</span>
	var number1 <span style="color: #993333;">int</span> <span style="color: #339933;">=</span> <span style="color: #0000dd;">8</span><span style="color: #339933;">;</span>
	<span style="color: #666666; font-style: italic;">// mas também pode ser assim</span>
	var number2 <span style="color: #339933;">=</span> <span style="color: #0000dd;">10</span><span style="color: #339933;">;</span>
	<span style="color: #666666; font-style: italic;">// ou assim</span>
	number3 <span style="color: #339933;">:=</span> <span style="color: #0000dd;">12</span><span style="color: #339933;">;</span>
&nbsp;
	fmt.<span style="color: #202020;">Printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Number1: %d<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> doubleIt<span style="color: #009900;">&#40;</span>number1<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	fmt.<span style="color: #202020;">Printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Number2: %d<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> doubleIt<span style="color: #009900;">&#40;</span>number2<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	fmt.<span style="color: #202020;">Printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Number3: %d<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> doubleIt<span style="color: #009900;">&#40;</span>number3<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Pode parecer muito revolucionário, mas não é! Dê uma olhada em <a href="http://www.haskell.org/">Haskell</a> ou <a href="http://www.erlang.org/">Erlang</a> e depois a gente conversa.</p>
<h1>Sem herança nem sobrecarga, e muito diferente</h1>
<p>Em Go, existe a noção de objetos, mas não do jeito tradicional, como visto por aí. Se bobear, alguns nem a chamem de orientado a objetos, afinal.</p>
<p>Primeiro, que não existe herança: todos os objetos não fazem parte de uma classe pai e nem há a possibilidade de classes filhas. Como consequência, a composição de objetos é a única forma possível de se trabalhar. E o mais interessante é que, sem heranças, uma grande Caixa de Pandora desaparece, porque:</p>
<ul>
<li><strong>os métodos e atributos <em><strong>protected</strong></em> vão embora:</strong> só existe visibilidade pública e privada ao pacote, e seu discernimento é feito da seguinte forma: quando um atributo ou método começa em letra maiúscula, é visível a todo mundo; quando minúscula, é protegido (mais sobre isso daqui a pouco).</li>
<li>Nada de atributo <strong>virtual</strong> que tanto enche quem programa em C# ou C++. Nada de depender do <em>“worst-case”</em> de outras linguagens que assumem que todo <em>dispatch</em> de métodos 	é dinâmico. Em Go, por objetos não terem filhos, todo <em>dispatch</em> de métodos é estático, a menos que você esteja usando uma referência à interface (mais sobre isso depois).</li>
</ul>
<p>Além do mais, diferente de Java e mais parecido com Python, o atributo <strong>this</strong> não é implícito. E não, não fica no primeiro parâmetro do método, mas num lugar especial, antes do nome do método. Também não há a noção de um escopo de classe onde todos os métodos ficam dentro. Em Go, primeiro é criada uma <strong>struct</strong>, e fora dela, os métodos – lembra um pouco Javascript.</p>
<p>Pra não ficarem boiando, um exemplo de uma classe <em>Time</em> simplificada, que exibe horas e minutos:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">package mytime
&nbsp;
import <span style="color: #ff0000;">&quot;fmt&quot;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// os atributos de uma classe ficam numa struct</span>
type Time <span style="color: #993333;">struct</span> <span style="color: #009900;">&#123;</span>
	hour uint<span style="color: #339933;">;</span>
	minute uint<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// método &quot;solto&quot; que cria um Time.</span>
<span style="color: #666666; font-style: italic;">// repare que, por iniciar em letra minúscula,</span>
<span style="color: #666666; font-style: italic;">// só codigos sobre o pacote mytime podem acessá-lo</span>
func newTime<span style="color: #009900;">&#40;</span>hour uint<span style="color: #339933;">,</span> minute uint<span style="color: #009900;">&#41;</span> <span style="color: #339933;">*</span>Time <span style="color: #009900;">&#123;</span>
	<span style="color: #666666; font-style: italic;">// um jeito de iniciar uma struct</span>
	t <span style="color: #339933;">:=</span> Time <span style="color: #009900;">&#123;</span><span style="color: #0000dd;">0</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
	<span style="color: #666666; font-style: italic;">// minutos - overflow em hora</span>
	t.<span style="color: #202020;">minute</span> <span style="color: #339933;">=</span> minute <span style="color: #339933;">%</span> <span style="color: #0000dd;">60</span><span style="color: #339933;">;</span>
	t.<span style="color: #202020;">hour</span> <span style="color: #339933;">=</span> minute <span style="color: #339933;">/</span> <span style="color: #0000dd;">60</span><span style="color: #339933;">;</span>
	<span style="color: #666666; font-style: italic;">// horas - ignora overflow</span>
	t.<span style="color: #202020;">hour</span> <span style="color: #339933;">+=</span> hour <span style="color: #339933;">%</span> <span style="color: #0000dd;">24</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #b1b100;">return</span> <span style="color: #339933;">&amp;</span>t<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// método de fábrica</span>
<span style="color: #666666; font-style: italic;">// não existe construtor de objetos</span>
<span style="color: #666666; font-style: italic;">// letra maiúscula indica que é método público</span>
func Create<span style="color: #009900;">&#40;</span>hour uint<span style="color: #339933;">,</span> minute uint<span style="color: #009900;">&#41;</span> <span style="color: #339933;">*</span>Time <span style="color: #009900;">&#123;</span>
	<span style="color: #b1b100;">return</span> newTime<span style="color: #009900;">&#40;</span>hour<span style="color: #339933;">,</span> minute<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// aqui é que fica interessante</span>
<span style="color: #666666; font-style: italic;">// este método torna-se membro de Time ao declará-lo como receptor</span>
<span style="color: #666666; font-style: italic;">// (declaração antes do nome do método)</span>
func <span style="color: #009900;">&#40;</span>t <span style="color: #339933;">*</span>Time<span style="color: #009900;">&#41;</span> AddMinute<span style="color: #009900;">&#40;</span>min uint<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	totalMin <span style="color: #339933;">:=</span> t.<span style="color: #202020;">minute</span> <span style="color: #339933;">+</span> min<span style="color: #339933;">;</span>
	t.<span style="color: #202020;">minute</span> <span style="color: #339933;">=</span> totalMin <span style="color: #339933;">%</span> <span style="color: #0000dd;">60</span><span style="color: #339933;">;</span>
&nbsp;
	t.<span style="color: #202020;">AddHour</span><span style="color: #009900;">&#40;</span>totalMin <span style="color: #339933;">/</span> <span style="color: #0000dd;">60</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
func <span style="color: #009900;">&#40;</span>t <span style="color: #339933;">*</span>Time<span style="color: #009900;">&#41;</span> AddHour<span style="color: #009900;">&#40;</span>hour uint<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	totalHour <span style="color: #339933;">:=</span> t.<span style="color: #202020;">hour</span> <span style="color: #339933;">+</span> hour<span style="color: #339933;">;</span>
	t.<span style="color: #202020;">hour</span> <span style="color: #339933;">=</span> totalHour <span style="color: #339933;">%</span> <span style="color: #0000dd;">24</span><span style="color: #339933;">;</span>		
<span style="color: #009900;">&#125;</span>
&nbsp;
func <span style="color: #009900;">&#40;</span>t <span style="color: #339933;">*</span> Time<span style="color: #009900;">&#41;</span> Increment<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	t.<span style="color: #202020;">AddMinute</span><span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// os métodos de print chamam esse método</span>
func <span style="color: #009900;">&#40;</span>time <span style="color: #339933;">*</span>Time<span style="color: #009900;">&#41;</span> String<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #993333;">string</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #b1b100;">return</span> fmt.<span style="color: #202020;">Sprintf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%02d:%02d&quot;</span><span style="color: #339933;">,</span> time.<span style="color: #202020;">hour</span><span style="color: #339933;">,</span> time.<span style="color: #202020;">minute</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Ah, ia me esquecendo! As interfaces! Um exemplo que eu precisei fazer é criar um tipo standardInput que lê do <em>File Descriptor</em> 0 (zero) (em Unix, 0 é <em>sdtin</em>, 1 é <em>stdout</em> e 2 é <em>stderr</em>), porque não existe um método <em>scanf</em>, como em C.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// tipo necessário para o reader do bufio,</span>
<span style="color: #666666; font-style: italic;">// que aceita qualquer classe com interface io.Reader		</span>
type standardInput <span style="color: #993333;">struct</span> <span style="color: #009900;">&#123;</span>
&nbsp;
<span style="color: #009900;">&#125;</span>
&nbsp;
func <span style="color: #009900;">&#40;</span>si <span style="color: #339933;">*</span>standardInput<span style="color: #009900;">&#41;</span> Read<span style="color: #009900;">&#40;</span>p <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span>uint8<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#40;</span>n <span style="color: #993333;">int</span><span style="color: #339933;">,</span> err os.<span style="color: #202020;">Error</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	r<span style="color: #339933;">,</span> e <span style="color: #339933;">:=</span> syscall.<span style="color: #202020;">Read</span><span style="color: #009900;">&#40;</span><span style="color: #0000dd;">0</span><span style="color: #339933;">,</span> p<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #b1b100;">if</span> e <span style="color: #339933;">!=</span> <span style="color: #0000dd;">0</span> <span style="color: #009900;">&#123;</span>
		err <span style="color: #339933;">=</span> os.<span style="color: #202020;">Errno</span><span style="color: #009900;">&#40;</span>e<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #b1b100;">return</span> <span style="color: #993333;">int</span><span style="color: #009900;">&#40;</span>r<span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> err<span style="color: #339933;">;</span>		
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Não tem nada de <strong>implements</strong> aí, mas o tipo já implementa a interface <a href="http://golang.org/pkg/io/#Reader">io.Reader</a>, apenas porque aquele realiza o mesmo método deste. Isso tanto é verdade que quando é usado como parâmetro para <a href="http://golang.org/pkg/bufio/#Reader.NewReader">bufio.NewReader</a>, não ocorre problemas.</p>
<h1>Com paralelismo mais fácil, o design muda</h1>
<p><strong><em>Goroutines</em></strong> é o jeito da linguagem implementar paralelismo. Não chega a ser tão &#8220;na unha&#8221; quanto a <a href="http://java.sun.com/javase/6/docs/api/java/lang/Thread.html">Thread</a> em Java ou a <a href="http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html">pthread</a> em C/Posix, mas não é tão alto nível quanto o modelo de atores implementado em Erlang ou Scala.</p>
<p>Uma <em>goroutine</em> é um método que roda em <em>background</em>, e que não avisa ninguém quando termina a execução. Não existe uma comunicação entre o chamador e o chamado, a não ser com o uso de <em>channels</em>: uma estrutura síncrona e bidirecional para troca de mensagens. Como comparação, parece igual ao C, onde é possível dar um <em>fork</em> no processo (criar <em>goroutine</em>), e depois fazer comunicação entre si através de <em>pipes</em> (<em>channels</em>). Porém, com Go é muito mais fácil e flexível.</p>
<p><em>Goroutine</em> lembra apenas vagamente o modelo de <strong><em>coroutines</em></strong> em Python (com seu <em>yield</em>, <em>next</em> e <em>send</em>), ou o modelo de <strong>Fibers</strong> do Ruby 1.9. Nesses, a diferença é que não existem <em>channels</em>, porque os métodos de envio e recebimentos de mensagens fazem parte da referência da <em>coroutine</em>.</p>
<p>Acredito que, apesar de <em>goroutine</em> estar associado à otimização de aplicativos que rodam em múltiplos <em>cores</em>, a grande vantagem pode ser uma melhor modularização das aplicações. Já vi idéias de se usar uma corrotina para separar códigos com estados mutáveis dos não-mutáveis, mas isso eu discutiria num outro post. Por hora, resolvi fazer uma aplicação interativa que pergunta ao usuário como manipular a hora (classe definida anteriormente). Resolvi fazer uma <em>goroutine</em> que isola o <em>input-output</em> do restante da aplicação. Sim, com certeza, não vai melhorar a execução paralela, mas modulariza melhor. Primeiro, a parte do <em>input-output</em> no código abaixo:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">package iocontrol
&nbsp;
import <span style="color: #009900;">&#40;</span>
	<span style="color: #ff0000;">&quot;bufio&quot;</span><span style="color: #339933;">;</span>
	<span style="color: #ff0000;">&quot;syscall&quot;</span><span style="color: #339933;">;</span>
	<span style="color: #ff0000;">&quot;fmt&quot;</span><span style="color: #339933;">;</span>
	<span style="color: #ff0000;">&quot;os&quot;</span><span style="color: #339933;">;</span>
	<span style="color: #ff0000;">&quot;strings&quot;</span><span style="color: #339933;">;</span>
	<span style="color: #ff0000;">&quot;strconv&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#41;</span>
&nbsp;
&nbsp;
type Query <span style="color: #993333;">struct</span> <span style="color: #009900;">&#123;</span>
	What <span style="color: #993333;">string</span><span style="color: #339933;">;</span>
	HowMany uint<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// tipo necessário para o reader do bufio,</span>
<span style="color: #666666; font-style: italic;">// que aceita qualquer classe com interface io.Reader		</span>
type standardInput <span style="color: #993333;">struct</span> <span style="color: #009900;">&#123;</span>
&nbsp;
<span style="color: #009900;">&#125;</span>
&nbsp;
func <span style="color: #009900;">&#40;</span>si <span style="color: #339933;">*</span>standardInput<span style="color: #009900;">&#41;</span> Read<span style="color: #009900;">&#40;</span>p <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span>uint8<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#40;</span>n <span style="color: #993333;">int</span><span style="color: #339933;">,</span> err os.<span style="color: #202020;">Error</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	r<span style="color: #339933;">,</span> e <span style="color: #339933;">:=</span> syscall.<span style="color: #202020;">Read</span><span style="color: #009900;">&#40;</span><span style="color: #0000dd;">0</span><span style="color: #339933;">,</span> p<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #b1b100;">if</span> e <span style="color: #339933;">!=</span> <span style="color: #0000dd;">0</span> <span style="color: #009900;">&#123;</span>
		err <span style="color: #339933;">=</span> os.<span style="color: #202020;">Errno</span><span style="color: #009900;">&#40;</span>e<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #b1b100;">return</span> <span style="color: #993333;">int</span><span style="color: #009900;">&#40;</span>r<span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> err<span style="color: #339933;">;</span>		
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// converte uma string para o tipo Query</span>
func ToQuery<span style="color: #009900;">&#40;</span>line <span style="color: #993333;">string</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">*</span>Query <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// separando a linha em dois valores</span>
	arr <span style="color: #339933;">:=</span> strings.<span style="color: #202020;">Split</span><span style="color: #009900;">&#40;</span>line<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;:&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">2</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	var what <span style="color: #993333;">string</span> <span style="color: #339933;">=</span> <span style="color: #ff0000;">&quot;&quot;</span><span style="color: #339933;">;</span>
	<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>len<span style="color: #009900;">&#40;</span>arr<span style="color: #009900;">&#41;</span> <span style="color: #339933;">&gt;=</span> <span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #666666; font-style: italic;">// o primeiro é uma string sem espaços em volta</span>
		what <span style="color: #339933;">=</span> strings.<span style="color: #202020;">TrimSpace</span><span style="color: #009900;">&#40;</span>arr<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// não havendo uma string com dois pontos no meio,</span>
	<span style="color: #666666; font-style: italic;">// o array tem tamanho 1</span>
	var howMany uint <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
	<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>len<span style="color: #009900;">&#40;</span>arr<span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #0000dd;">2</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #666666; font-style: italic;">// o segundo é um número</span>
		var err os.<span style="color: #202020;">Error</span><span style="color: #339933;">;</span>
		howMany<span style="color: #339933;">,</span> err <span style="color: #339933;">=</span> strconv.<span style="color: #202020;">Atoui</span><span style="color: #009900;">&#40;</span>
			strings.<span style="color: #202020;">TrimSpace</span><span style="color: #009900;">&#40;</span>arr<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>err <span style="color: #339933;">!=</span> nil<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			fmt.<span style="color: #202020;">Println</span><span style="color: #009900;">&#40;</span>err<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #666666; font-style: italic;">// criando a estrutura Query</span>
	<span style="color: #b1b100;">return</span> <span style="color: #339933;">&amp;</span>Query<span style="color: #009900;">&#123;</span>what<span style="color: #339933;">,</span> howMany<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
func IOControl<span style="color: #009900;">&#40;</span>channel chan <span style="color: #993333;">string</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #b1b100;">for</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #666666; font-style: italic;">// obtendo do channel a resposta a ser exibida</span>
		<span style="color: #666666; font-style: italic;">// na tela</span>
		output <span style="color: #339933;">:=</span> <span style="color: #339933;">&lt;-</span>channel<span style="color: #339933;">;</span>
&nbsp;
		fmt.<span style="color: #202020;">Println</span><span style="color: #009900;">&#40;</span>output<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #666666; font-style: italic;">// lendo a linha de comando</span>
		reader <span style="color: #339933;">:=</span> bufio.<span style="color: #202020;">NewReader</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span>standardInput<span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		line<span style="color: #339933;">,</span> err <span style="color: #339933;">:=</span> reader.<span style="color: #202020;">ReadString</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">'<span style="color: #000099; font-weight: bold;">\n</span>'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #b1b100;">if</span> err <span style="color: #339933;">==</span> nil <span style="color: #009900;">&#123;</span>
			channel <span style="color: #339933;">&lt;-</span> line<span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
			channel <span style="color: #339933;">&lt;-</span> <span style="color: #ff0000;">&quot;error:0&quot;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>O código que vai virar uma <em>goroutine</em> é o último aí em cima, o <strong>IOControl</strong>. No código principal abaixo, será criado o <em>channel</em> e a <em>goroutine</em> para execução.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">package main
&nbsp;
import <span style="color: #009900;">&#40;</span>
	<span style="color: #ff0000;">&quot;fmt&quot;</span><span style="color: #339933;">;</span>
	<span style="color: #ff0000;">&quot;./mytime&quot;</span><span style="color: #339933;">;</span>
	<span style="color: #ff0000;">&quot;./iocontrol&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#41;</span>
&nbsp;
func main<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// criando um channel</span>
	var io <span style="color: #339933;">=</span> make<span style="color: #009900;">&#40;</span>chan <span style="color: #993333;">string</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #666666; font-style: italic;">// e criando uma goroutine</span>
	go iocontrol.<span style="color: #202020;">IOControl</span><span style="color: #009900;">&#40;</span>io<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	time <span style="color: #339933;">:=</span> mytime.<span style="color: #202020;">Create</span><span style="color: #009900;">&#40;</span><span style="color: #0000dd;">0</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	fmt.<span style="color: #202020;">Println</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Possible commands:<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>
		<span style="color: #ff0000;">&quot;hour : n<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>
		<span style="color: #ff0000;">&quot;minute : n<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>
		<span style="color: #ff0000;">&quot;tick<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>
		<span style="color: #ff0000;">&quot;exit<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #666666; font-style: italic;">// mandando o time em String para o channel &quot;io&quot;</span>
	io <span style="color: #339933;">&lt;-</span> time.<span style="color: #202020;">String</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	loop<span style="color: #339933;">:</span> <span style="color: #b1b100;">for</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #666666; font-style: italic;">// obtendo do channel uma string do próximo pedido</span>
		query <span style="color: #339933;">:=</span> iocontrol.<span style="color: #202020;">ToQuery</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">&lt;-</span>io<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #666666; font-style: italic;">// &quot;switch&quot; em Go não requer &quot;break&quot;</span>
		<span style="color: #b1b100;">switch</span> query.<span style="color: #202020;">What</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">case</span> <span style="color: #ff0000;">&quot;hour&quot;</span><span style="color: #339933;">:</span>
			time.<span style="color: #202020;">AddHour</span><span style="color: #009900;">&#40;</span>query.<span style="color: #202020;">HowMany</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #b1b100;">case</span> <span style="color: #ff0000;">&quot;minute&quot;</span><span style="color: #339933;">:</span>
			time.<span style="color: #202020;">AddMinute</span><span style="color: #009900;">&#40;</span>query.<span style="color: #202020;">HowMany</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #b1b100;">case</span> <span style="color: #ff0000;">&quot;tick&quot;</span><span style="color: #339933;">:</span>
			time.<span style="color: #202020;">Increment</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #b1b100;">case</span> <span style="color: #ff0000;">&quot;error&quot;</span><span style="color: #339933;">:</span>
			fmt.<span style="color: #202020;">Println</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;an error occurred&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #b1b100;">case</span> <span style="color: #ff0000;">&quot;exit&quot;</span><span style="color: #339933;">:</span>
			<span style="color: #000000; font-weight: bold;">break</span> loop<span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		io <span style="color: #339933;">&lt;-</span> time.<span style="color: #202020;">String</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Executando-o, será perguntado como e quanto a acrescentar na hora atual, até que você digite <em>exit</em>.</p>
<p>Preciso dizer também que não é difícil cometer erros na programação paralela. Eu por exemplo, esqueci de por o conteúdo de <strong>IOControl</strong> dentro de um laço infinito. E aí, com a <em>thread</em> morta após a primeira rodada de resposta e pergunta, o <em>channel</em> foi bloqueado na escrita sem ninguém pra ler. Com isso, a aplicação em entrou em <em>deadlock</em>, havendo a interrupção do programa com o erro na tela. Ou seja, não é tão desgraçado quanto Thread, mas fique atento.</p>
<h1>Sem exceção, literalmente</h1>
<p>Talvez isso decepcione alguns, mas a linguagem Go não tem <em>exceptions</em>. Ainda não digeri bem essa notícia, mas existem coisas que fazem com que essa linguagem não caia na armadilha do C.</p>
<p>Uma é que o <em>“finally”</em> pode ser substituído pelo <strong>defer</strong>, que indica o comando que precisa ser invocado incondicionalmente antes da saída do método. Outra, é que, como em Go é possível haver múltiplos retornos, criam-se métodos com dois retornos, o primeiro sendo o conteúdo normal e o segundo o código de erro (se houver).  Assim:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">&nbsp;
package main
&nbsp;
import <span style="color: #009900;">&#40;</span>
	<span style="color: #ff0000;">&quot;os&quot;</span><span style="color: #339933;">;</span>
	<span style="color: #ff0000;">&quot;io&quot;</span><span style="color: #339933;">;</span>
	<span style="color: #ff0000;">&quot;flag&quot;</span><span style="color: #339933;">;</span>
	<span style="color: #ff0000;">&quot;fmt&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#41;</span>
&nbsp;
func data<span style="color: #009900;">&#40;</span>name <span style="color: #993333;">string</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">string</span><span style="color: #339933;">,</span> os.<span style="color: #202020;">Error</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	var content <span style="color: #993333;">string</span> <span style="color: #339933;">=</span> <span style="color: #ff0000;">&quot;&quot;</span><span style="color: #339933;">;</span>
&nbsp;
	f<span style="color: #339933;">,</span> err <span style="color: #339933;">:=</span> os.<span style="color: #202020;">Open</span><span style="color: #009900;">&#40;</span>name<span style="color: #339933;">,</span> os.<span style="color: #202020;">O_RDONLY</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>err <span style="color: #339933;">==</span> nil<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		defer f.<span style="color: #202020;">Close</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		var rawContent <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span>byte <span style="color: #339933;">=</span> nil<span style="color: #339933;">;</span>
		rawContent<span style="color: #339933;">,</span> err <span style="color: #339933;">=</span> io.<span style="color: #202020;">ReadAll</span><span style="color: #009900;">&#40;</span>f<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		content <span style="color: #339933;">=</span> fmt.<span style="color: #202020;">Sprintf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%s&quot;</span><span style="color: #339933;">,</span> rawContent<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #b1b100;">return</span> content<span style="color: #339933;">,</span> err<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
func main<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	flag.<span style="color: #202020;">Parse</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	filename <span style="color: #339933;">:=</span> flag.<span style="color: #202020;">Arg</span><span style="color: #009900;">&#40;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	content<span style="color: #339933;">,</span> err <span style="color: #339933;">:=</span> data<span style="color: #009900;">&#40;</span>filename<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>err <span style="color: #339933;">==</span> nil<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		fmt.<span style="color: #202020;">Println</span><span style="color: #009900;">&#40;</span>content<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
		fmt.<span style="color: #202020;">Println</span><span style="color: #009900;">&#40;</span>err<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>O compilador impede que método com dois retornos seja associada a apenas uma variável (mesmo com tipo implícito). Então, supõe-se que o programador não tenha como esquecer de tratar os erros.</p>
<h1>Conclusão</h1>
<p>Go não é uma linguagem inovadora, mas pode ser um refresco para quem precisa de uma linguagem que tenha um contato próximo à máquina, e não quer depender de C ou C++. Nitidamente, é uma linguagem muito crua, e muitos anos de desenvolvimento precisam acontecer. Mas tem potencial.</p>
<p>P.S.: &#8220;Go With the Flow&#8221; é um rock do <em>Queens of the Stone Age</em>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.objectzilla.com.br/2009/11/21/go-with-the-flow/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

