Go (o golang ) es un lenguaje de programación creado en Google en 2007 por Robert Griesemer, Rob Pike y Ken Thompson. Es un lenguaje compilado, de tipo estático en la tradición de Algol y C.
Go tiene funciones de recolección de basura, tipificación estructural limitada, seguridad de la memoria y funciones de programación concurrente estilo CSP agregadas. El compilador y otras herramientas de lenguaje desarrolladas originalmente por Google son todas gratuitas y de código abierto.
La popularidad de Go está aumentando rápidamente. Es una excelente opción para crear aplicaciones web.
Para obtener más información, diríjase a la página de inicio de Go. ¿Quieres un recorrido rápido por Go? Consulte los documentos aquí.
Ahora veamos cómo instalar y comenzar con Go.
Instalación
Instale Golang con Homebrew:
$ brew update $ brew install golang
Instalación de Go en MacOS usando un tarball
Enlace a tarball
Puede obtener el enlace al archivo tarball de MacOS en la sección Latest Stable de la página de descarga de golang.
Proceso de instalación
En este proceso de instalación usaremos la última versión estable al momento de escribir este artículo (vaya a 1.9.1). Para una versión más nueva o anterior, simplemente reemplace el enlace en el primer paso. Consulte la página de descarga de golang para ver qué versiones están disponibles actualmente.
Instalación de Go 1.9.1
$ curl -O //storage.googleapis.com/golang/go1.9.1.darwin-amd64.tar.gz $ sudo tar -C /usr/local -xzf go1.9.1.darwin-amd64.tar.gz $ export PATH=$PATH:/usr/local/go/bin
Instale Golang en Ubuntu con apt
Usar el Source Package Manager (apt) de Ubuntu es una de las formas más fáciles de instalar Go. No obtendrá la última versión estable, pero para aprender esto debería ser suficiente.
$ sudo apt-get update $ sudo apt-get install golang-go
Verifique la instalación y versión de Go
Para comprobar si go se instaló correctamente, ejecute:
$ go version > go version go1.9.1 linux/amd64
Esto imprimirá la versión de Go que está instalada en la consola. Si ve una versión de Go, sabrá que la instalación se realizó sin problemas.
Configurar el espacio de trabajo
Agregar variables de entorno:
Primero, deberá indicarle a Go la ubicación de su espacio de trabajo.
Agregaremos algunas variables de entorno en la configuración de shell. Uno de los archivos does ubicados en su directorio de inicio bash_profile, bashrc o .zshrc (para Oh My Zsh Army)
$ vi .bashrc
luego agregue esas líneas para exportar las variables requeridas
Este es en realidad su archivo .bashrc
export GOPATH=$HOME/go-workspace # don't forget to change your path correctly! export GOROOT=/usr/local/opt/go/libexec export PATH=$PATH:$GOPATH/bin export PATH=$PATH:$GOROOT/bin
Crea tu espacio de trabajo
Cree el árbol de directorios del espacio de trabajo:
$ mkdir -p $GOPATH $GOPATH/src $GOPATH/pkg $GOPATH/bin $GOPATH/src : Where your Go projects / programs are located $GOPATH/pkg : contains every package objects $GOPATH/bin : The compiled binaries home
Inicio rápido
Para un proyecto Go de inicio rápido y repetitivo, pruebe Alloy.
- Repositorio de Clone Alloy
git clone //github.com/olliecoleman/alloy cd alloy
2. Instale las dependencias
glide install npm install
3. Inicie el servidor de desarrollo
go install alloy dev
4. Visite el sitio web en //localhost:1212
Alloy usa Node, NPM y Webpack.
El patio de recreo de Golang
Aprender a instalar Go en su máquina local es importante. Pero si quieres empezar a jugar con Go directamente en tu navegador, ¡Go Playground es la caja de arena perfecta para empezar de inmediato!
Just open a new browser window and go to the Playground.
Once there you’ll get the buttons:
- Run
- Format
- Imports
- Share
The Run button just sends the instructions for compiling the code you wrote to the Google servers that run the Golang back end.
The Format button implements the idiomatic formatting style of the language. You can read more about it here.
Imports just check what packages you have declared within import(). An import path is a string that uniquely identifies a package. A package’s import path corresponds to its location inside a workspace or in a remote repository (explained below). You can read more here.
With Share you get a URL where the code you just wrote is saved. This is useful when asking for help showing your code.
You can take a more in-depth Tour of Go here and learn more about the playground in the article Inside the Go Playground.
Go Maps
A map, called a dictionary in other languages, “maps” keys to values. A map is declared like this:
var m map[Key]Value
This map has no keys and no keys can be added to it. To create a map, use the make
function:
m = make(map[Key]Value)
Anything can be used as a key or as a value.
Modifying maps
Here are some common action with maps.
Inserting/Changing elements
Create or change element foo
in map m
:
m["foo"] = bar
Getting elements
Get element with key foo
in map m
:
element = m["foo"]
Deleting elements
Delete element with key foo
in map m
:
delete(m, "foo")
Check if a key has been used
Check if key foo
has been used in map m
:
element, ok = m["foo"]
If ok
is true
, the key has been used and element
holds the value at m["foo"]
. If ok
is false
, the key has not been used and element
holds its zero-values.
Map literals
You can directly create map literals:
var m = map[string]bool{ "Go": true, "JavaScript":false, } m["Go"] // true m["JavaScript"] = true // Set Javascript to true delete(m, "JavaScript") // Delete "JavaScript" key and value language, ok = m["C++"] // ok is false, language is bool's zero-value (false)
More info about Go:
- Learn Go in 7 hours with this free video course
- How to build a Twitter bot with Go