1643312280
Las variables de Golang son explícitamente declaradas y utilizadas por el compilador para verificar la corrección de tipos de las llamadas a funciones. Variable es el nombre dado a la ubicación de la memoria para almacenar el valor de un tipo particular. Existen numerosas sintaxis para declarar variables en go. Una variable es una ubicación de almacenamiento con un tipo particular y un nombre asociado.
Go variable es un marcador de posición de la información que se puede cambiar en tiempo de ejecución. La variable nos permite recuperar y manipular la información almacenada.
AppDividend, apps, _dividend // valid variable
123apps, '2appdividend // invalid variable
2. Un nombre de variable no debe comenzar con un dígito.
11appdividend // illegal variable
3. El nombre de la variable distingue entre mayúsculas y minúsculas.
apps and Apps are two different variables
4. No se permite el uso de palabras clave como nombre de variable.
5. No hay límite en la longitud del nombre de la variable, pero se recomienda utilizar una longitud óptima de 4 a 15 letras únicamente.
Uso de la palabra clave var: en el lenguaje Go, las variables se crean utilizando la palabra clave var de un tipo particular, conectado con el nombre y proporciona su valor inicial.
var variable_name type = expression
El tipo de nombre var es la sintaxis para declarar una sola variable.
package main
import "fmt"
func main() {
var series string // variable declare
fmt.Println(series)
}
La sentencia var series string declara la variable denominada series de tipo string . No hemos asignado ningún valor a la variable serie.
Si a una variable no se le asigna ningún valor, go la inicializa automáticamente con el valor vacío o 0 (si es un número entero) del tipo de variable. En este caso, a la serie se le asigna el valor vacío. Si la variable es un número entero, entonces se le asignará 0.
Si ejecuta el programa anterior, puede ver que el valor de la variable está vacío.
Consulte el siguiente código.
// hello.go
package main
import "fmt"
func main() {
var series string = "The Witcher"
fmt.Println(series)
}
go run hello.go
The Witcher
Veamos un ejemplo donde declaramos diferentes variables de tipo de datos.
// hello.go
package main
import "fmt"
func main() {
var game = 20
var kgb = "Stranger In Moscow"
var lockey = true
fmt.Printf("The value of game is : %d\n",
game)
fmt.Printf("The type of game is : %T\n",
game)
fmt.Printf("The value of kgb is : %s\n",
kgb)
fmt.Printf("The type of kgb is : %T\n",
kgb)
fmt.Printf("The value of lockey is : %t\n",
lockey)
fmt.Printf("The type of lockey is : %T\n",
lockey)
}
go run hello.go
The value of game is : 20
The type of game is : int
The value of kgb is : Stranger In Moscow
The type of kgb is : string
The value of lockey is : true
The type of lockey is : bool
Una variable se puede asignar a cualquier valor de su tipo de datos. En el programa anterior, al juego se le asigna un valor entero, KGB tiene un valor de cadena y lockey tiene un valor booleano.
Si la variable tiene un valor inicial, Go inferirá automáticamente el tipo de esa variable usando ese valor inicial. Por lo tanto, si la variable tiene un valor inicial, se puede omitir el tipo en la declaración de la variable.
Si una variable se declara usando la sintaxis var nombre = valor inicial , Golang inferirá automáticamente el tipo de esa variable a partir de un valor inicial. Go entenderá el tipo de variables inicializadas.
Consulte el siguiente código.
// hello.go
package main
import "fmt"
func main() {
var game = 20
fmt.Printf("The value of game is : %d\n",
game)
fmt.Printf("The type of game is : %T\n",
game)
}
En el código anterior, hemos definido una variable = 20, lo que significa que la variable del juego tiene un tipo entero porque 20 es un valor entero, por lo que no necesitamos definir su tipo de datos explícitamente.
Se pueden declarar múltiples variables en una sola declaración en Go.
La var nombre1, tipo nombre2 = valorinicial1, valorinicial2 es la sintaxis para la declaración de variables múltiples de Golang.
Consulte el siguiente código.
// hello.go
package main
import "fmt"
func main() {
var game, set = 1, 2
fmt.Printf("The value of game is : %d\n",
game)
fmt.Printf("The value of set is : %d\n",
set)
}
go run hello.go
The value of game is : 1
The value of set is : 2
Si no se define un valor inicial para las variables de juego y conjunto, tendrán asignado 0 como valor inicial.
// hello.go
package main
import "fmt"
func main() {
var game, set int
fmt.Printf("The value of game is : %d\n",
game)
fmt.Printf("The value of set is : %d\n",
set)
}
go run hello.go
The value of game is : 0
The value of set is : 0
Golang también proporciona otra forma concisa de declarar variables. Esto se conoce como declaración abreviada y utiliza el operador := .
Las variables locales que se declaran e inicializan en las funciones se declaran mediante una declaración de variable breve.
La declaración abreviada requiere valores iniciales para todas las variables en el lado izquierdo de la asignación.
Consulte la sintaxis de declaración de variable corta.
variable_name:= expression
Consulte el siguiente código.
// hello.go
package main
import "fmt"
func main() {
askingPrice := 100
payingPrice := 50
fmt.Println("Asking Price is", askingPrice, "Paying price is", payingPrice)
}
go run hello.go
Asking Price is 100 Paying price is 50
La mayoría de las variables locales se declaran e inicializan mediante declaraciones de variables cortas debido a su brevedad y flexibilidad.
La declaración de variables var se utiliza para aquellas variables locales que necesitan un tipo explícito que difiera de la expresión del inicializador o para aquellas variables cuyos valores se asignan más tarde, y el valor inicializado no es importante.
Usando una declaración de variable corta, puede declarar múltiples variables en una sola declaración.
La sintaxis abreviada solo se puede usar cuando al menos una de las variables en el lado izquierdo de := se declara por primera vez. Consulte el siguiente código.
// hello.go
package main
import "fmt"
func main() {
el, mike := 11, 21
fmt.Println("el is", el, "mike is", mike)
mike, kb := 10, 19
fmt.Println("mike is", mike, "kb is", kb)
mike, kb = 30, 46
fmt.Println("changed mike is", mike, "kb is", kb)
}
go run hello.go
el is 11 mike is 21
mike is 10 kb is 19
changed mike is 30 kb is 46
Consulte el siguiente código.
// hello.go
package main
import "fmt"
func main() {
name, series, age := "Millie", "Stanger Things", 16
fmt.Println("Name is", name)
fmt.Println("Series is", series)
fmt.Println("Age is", age)
}
go run hello.go
Name is Millie
Series is Stanger Things
Age is 16
Usando una declaración de variable corta, puede declarar múltiples variables de diferentes tipos en una sola declaración. La expresión determina el tipo de estas variables.
En Golang, podemos declarar una variable sin un valor inicial, con un valor inicial, con sintaxis abreviada o directamente asignar el valor al valor sin declarar una variable.
1599854400
Go announced Go 1.15 version on 11 Aug 2020. Highlighted updates and features include Substantial improvements to the Go linker, Improved allocation for small objects at high core counts, X.509 CommonName deprecation, GOPROXY supports skipping proxies that return errors, New embedded tzdata package, Several Core Library improvements and more.
As Go promise for maintaining backward compatibility. After upgrading to the latest Go 1.15 version, almost all existing Golang applications or programs continue to compile and run as older Golang version.
#go #golang #go 1.15 #go features #go improvement #go package #go new features
1655304840
Building Web Applications with Go
Welcome, gopher! You're not a gopher? Well, this workshop is for gophers, or people that use the Go programming language. But fear not if you've never written any Go before! I'd recommend you learn the basics for the language first with the Go tour.
This workshop has been run a couple of times with an instructor leading. The goal of this repo is to make it as easy as possible for individuals to follow the content by themselves. If you get stuck at any point, feel free to file issues asking questions.
To go through this you will need the following:
GOPATH
by following the How to Write Go Code tutorial.There's a lot to say about how to build web applications, in Go or any other language. But we only have one day so we won't try to cover too much. Instead we'll cover the basics, so you'll be able to explore other solutions and frameworks later.
The workshops is divided in eleven sections:
These are places where you can find more information for Go:
My favorite aspect of Go is its community, and you are now part of it too. Welcome!
As a newcomer to the Go community you might have questions or get blocked at some point. This is completely normal, and we're here to help you. Some of the places where gophers tend to hang out are:
This is not an official Google product (experimental or otherwise), it is just code that happens to be owned by Google.
Author: Campoy
Source Code: https://github.com/campoy/go-web-workshop
License: Apache-2.0 license
1599732000
We spoke to Rob Pike, the co-author of the Go programming language, about a career spanning four decades, the evolution of Go over the last ten years, and into the future.
Evrone: Unlike many developers today, you started your career decades ago at Bell Labs. What’s been the biggest change in the way we develop software that you can think of, given your rare perspective?
**Rob: **The scale is much bigger today. Not just of the computers and the network, but the programs themselves. All of Unix version 6 (circa 1975) fits comfortably on a single RK05 disk pack, which has just over 2MB of storage, with lots of room left over for user software. And that was a fine computing environment, or at least seemed like one at the time. Although I can, of course, explain much of the growth, it is astonishing and perhaps not all of it is justified.
#golang #golang-api #golang-tools #golang-website #rob-pike #interview-transcript-go #latest-tech-stories #cloud-infrastructure-and-go
1596793260
http
package to create and initialize HTTPS servers in Go.(source: unsplash.com)
In the “Simple Hello World Server” lesson, we learned about net/http
package, how to create routes and how [ServeMux](https://golang.org/pkg/net/http/#ServeMux)
works. In the “Running multiple HTTP servers” lesson, we learned about [Server](https://golang.org/pkg/net/http/#Server)
structure and how to run multiple HTTP servers concurrently.
In this lesson, we are going to create an HTTPS server using both Go’s standard server configuration and custom configuration (using [_Server_](https://golang.org/pkg/net/http/#Server)
structure). But before this, we need to know what HTTPS really is?
HTTPS is a big topic of discussion in itself. Hence while writing this lesson, I published an article just on “How HTTPS works?”. I advise you to read this lesson first before continuing this article. In this article, I’ve also described the encryption paradigm and SSL certificates generation process.
If we recall the simplest HTTP server example from previous lessons, we only need http.``[ListenAndServe](https://golang.org/pkg/net/http/#ListenAndServe)
function to start an HTTP server and http.``[HandleFunc](https://golang.org/pkg/net/http/#HandleFunc)
to register a response handler for a particular endpoint.
(https://play.golang.org/p/t3sOenOYAzS)
In the example above, when we run the command go run server.go
, it will start an HTTP server on port 9000
. By visiting http://localhost:9000
URL in a browser, you will be able to see a Hello World!
message on the screen.
As we know, the nil
argument to ListenAndServe()
call invokes Go to use the [DefaultServeMux](https://golang.org/pkg/net/http/#DefaultServeMux)
response multiplexer, which is the default instance of ServeMux
structure provided globally by the Go. The HandleFunc()
call adds a response handler for a specific route on the multiplexer instance.
The http.ListenAndServe()
call uses the Go’s standard HTTP server configuration, however, in the previous lesson, how we can customize a server using [Server](https://golang.org/pkg/net/http/#Server)
structure type.
To start an HTTPS server, all we need do is to call ServerAndListenTLS
method with some configuration. Just like ServeAndListen
method, this method is available on both the http
package and the Server
structure.
The http.``[ServeAndListenTLS](https://golang.org/pkg/net/http/#ListenAndServeTLS)
method uses the Go’s standard server implementation, however, both [Server](https://golang.org/pkg/net/http/#Server)
instance and Server.``[ServeAndListenTLS](https://golang.org/pkg/net/http/#Server.ListenAndServeTLS)
method can be configured for our needs.
#go-programming-language #go #golang-tutorial #go-programming #golang
1665485400
Here is a reading list of blog posts about Go. It aspires to include only the most useful and relevant material that anyone writing Go should eventually read. By definition, the list is a work in progress.
Rather than being comprehensive, the list is a curated selection fixed at 200 entries.
Go is growing fast and so are the number of blog posts about it. If an interested reader knows of a great post not on this list, please open an issue with a link to the post. Not every blog post linked in an issue will make its way into the list. Nonetheless, the issue list (both open and closed) is a good source of additional reading material.
NOTE: Any new additions will need to replace something else on the list to keep it at a fixed length.
See Go Books for a list of books, both free and paid.
Author: Enocom
Source Code: https://github.com/enocom/gopher-reading-list
License: Apache-2.0 license