mirror of
https://github.com/MichaelCade/90DaysOfDevOps.git
synced 2025-03-10 04:48:50 +07:00
Translated to Spanish the day11 file
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
This commit is contained in:
parent
56a6c9b0fc
commit
8a2234fda9
102
es/Days/day11.md
102
es/Days/day11.md
@ -1,28 +1,28 @@
|
||||
Before we get into the topics for today I want to give a massive shout out to [Techworld with Nana](https://www.youtube.com/watch?v=yyUHQIec83I) and this fantastic concise journey through the fundamentals of Go.
|
||||
Antes de empezar con los temas de hoy mandamos un gran saludo a [Techworld con Nana](https://www.youtube.com/watch?v=yyUHQIec83I) y a ese fantástico y conciso viaje a través de los fundamentos básicos de Go.
|
||||
|
||||
On [Day8](day08.md) we set our environment up, on [Day9](day09.md) we walked through the Hello #90DaysOfDevOps code and on [Day10](day10.md)) we looked at our Go workspace and went a little deeper into compiling and running the code.
|
||||
En el [Día 8](day08.md) configuramos nuestro entorno, en el [Día 9](day09.md) recorrimos el código de Hello #90DaysOfDevOps y en el [Día 10](day10.md)) vimos nuestro workspace Go y profundizamos un poco sobre la compilación y ejecución del código.
|
||||
|
||||
Today we are going to take a look into Variables, Constants and Data Types whilst writing a new program.
|
||||
Hoy vamos a echar un vistazo a las Variables, Constantes y Tipos de Datos escribiendo un nuevo programa.
|
||||
|
||||
## Variables & Constants in Go
|
||||
## Variables y Constantes en Go
|
||||
|
||||
Let's start by planning our application, I think it would be a good idea to work on a program that tells us how many days we have remained in our #90DaysOfDevOps challenge.
|
||||
Empecemos por planificar nuestra aplicación, parece una buena idea trabajar en un programa que nos diga cuántos días hemos permanecido en nuestro reto #90DaysOfDevOps.
|
||||
|
||||
The first thing to consider here is that as we are building our app and we are welcoming our attendees and we are giving the user feedback on the number of days they have completed we might use the term #90DaysOfDevOps many times throughout the program. This is a great use case to make #90DaysOfDevOps a variable within our program.
|
||||
Lo primero que hay que tener en cuenta aquí es que a medida que construyamos nuestra app, demos la bienvenida a nuestros asistentes y vayamos dando el feedback al usuario sobre el número de días que ha completado, a lo largo del programa, podríamos utilizar el término #90DaysOfDevOps muchas veces. Así que aquí tenemos una oportunidad de hacer una variables con #90DaysOfDevOps para nuestro programa.
|
||||
|
||||
- Variables are used to store values.
|
||||
- Like a little box with our saved information or values.
|
||||
- We can then use this variable across the program which also benefits that if this challenge or variable changes then we only have to change this in one place. This means we could translate this to other challenges we have in the community by just changing that one variable value.
|
||||
- Las variables se utilizan para almacenar valores.
|
||||
- Son como una pequeña caja con nuestra información o valores guardados (Así lo explican todos los docentes a quienes empiezan 😊).
|
||||
- Podremos utilizar esta variable en todo el programa, lo que también beneficia a que si este reto o la variable cambia, sólo tendremos que cambiar el valor en un solo lugar. Esto significa que podemos trasladar esto a otros retos que tenemos en la comunidad con sólo cambiar el valor de esa variable.
|
||||
|
||||
To declare this in our Go Program we define a value by using a **keyword** for variables. This will live within our `func main` block of code that you will see later. You can find more about [Keywords](https://go.dev/ref/spec#Keywords)here.
|
||||
Para declarar esto en nuestro programa Go definimos un valor utilizando una **keywords** para las variables. Esto permanecerá dentro de nuestro bloque de código `func main` que verás más adelante. Puedes encontrar más información sobre Keywords [aquí](https://go.dev/ref/spec#Keywords).
|
||||
|
||||
Remember to make sure that your variable names are descriptive. If you declare a variable you must use it or you will get an error, this is to avoid possible dead code, code that is never used. This is the same for packages not used.
|
||||
Recuerda asegurarte de que los nombres de tus variables sean descriptivos. Si declaras una variable debes usarla o recibirás un error, esto es para evitar posible dead code, código que nunca se usa. Lo mismo ocurre con los paquetes que no se utilizan.
|
||||
|
||||
```
|
||||
var challenge = "#90DaysOfDevOps"
|
||||
```
|
||||
|
||||
With the above set and used as we will see in the next code snippet you can see from the output below that we have used a variable.
|
||||
Con lo anterior establecido vamos a utilizarlo en el siguiente fragmento de código. Se puede ver en la salida de abajo que hemos utilizado la variable.
|
||||
|
||||
```
|
||||
package main
|
||||
@ -35,15 +35,15 @@ func main() {
|
||||
}
|
||||
```
|
||||
|
||||
You can find the above code snippet in [day11_example1.go](Go/day11_example1.go)
|
||||
Puedes encontrar el código anterior en el fichero [day11_example1.go](Go/day11_example1.go).
|
||||
|
||||
You will then see from the below that we built our code with the above example and we got the output shown below.
|
||||
A continuación verás que hemos construido nuestro código con el ejemplo anterior y hemos obtenido la salida que se muestra a continuación.
|
||||
|
||||

|
||||
|
||||
We also know that our challenge is 90 days at least for this challenge, but next, maybe it's 100 so we want to define a variable to help us here as well. However, for our program, we want to define this as a constant. Constants are like variables, except that their value cannot be changed within code (we can still create a new app later on down the line with this code and change this constant but this 90 will not change whilst we are running our application)
|
||||
Sabemos que este reto en concreto es de 90 días, pero el próximo, quizás sea de 100 por lo que definiremos una variable que nos ayude aquí también. Sin embargo, para nuestro programa, queremos definirla como una constante. Las constantes son como las variables, excepto que su valor no puede ser cambiado dentro del código (aunque podemos crear una nueva aplicación más adelante con el mismo código y cambiar la constante. El 90 no cambiará mientras estemos ejecutando esta aplicación)
|
||||
|
||||
Adding the `const` to our code and adding another line of code to print this.
|
||||
Añadiendo `const` a nuestro código y añadiendo otra línea de código para imprimir esto.
|
||||
|
||||
```
|
||||
package main
|
||||
@ -59,15 +59,15 @@ func main() {
|
||||
}
|
||||
```
|
||||
|
||||
You can find the above code snippet in [day11_example2.go](Go/day11_example2.go)
|
||||
Puedes encontrar el código anterior en[day11_example2.go](Go/day11_example2.go).
|
||||
|
||||
If we then go through that `go build` process again and run you will see below the outcome.
|
||||
Si a continuación volvemos a pasar por ese proceso de `go build` y lo ejecutamos veremos a continuación el resultado.
|
||||
|
||||

|
||||
|
||||
Finally, and this won't be the end of our program we will come back to this in [Day12](day12.md) to add more functionality. We now want to add another variable for the number of days we have completed the challenge.
|
||||
Por último añadiremos otra variable para el número de días que hemos completado. Pero esto no será el final de nuestro programa, seguiremos con nuestro programa el [Día 12](day12.md) para añadir más funcionalidad.
|
||||
|
||||
Below I added the `dayscomplete` variable with the number of days completed.
|
||||
A continuación verás añadida la variable `dayscomplete` con el número de días completados.
|
||||
|
||||
```
|
||||
package main
|
||||
@ -85,17 +85,19 @@ func main() {
|
||||
}
|
||||
```
|
||||
|
||||
You can find the above code snippet in [day11_example3.go](Go/day11_example3.go)
|
||||
Puedes encontrar el código anterior en [day11_example3.go](Go/day11_example3.go)
|
||||
|
||||
Let's run through that `go build` process again or you could just use `go run`
|
||||
Volvamos a ejecutar compilando con `go build` y ejecutando el fichero compilado o directamente usando `go run`.
|
||||
|
||||

|
||||
|
||||
Here are some other examples that I have used to make the code easier to read and edit. We have up till now been using `Println` but we can simplify this by using `Printf` by using `%v` which means we define our variables in order at the end of the line of code. we also use `\n` for a line break.
|
||||
Aquí hay algunos ejemplos para hacer el código más fácil de leer y editar. Hasta ahora hemos estado usando `Println` pero podemos simplificar cambiando el `Printf` por `%v` lo que definirá nuestras variables en orden al final de la línea de código. También vamos a usar `\n` para un salto de línea.
|
||||
|
||||
I am using `%v` as this uses a default value but there are other options that can be found here in the [fmt package documentation](https://pkg.go.dev/fmt) you can find the code example [day11_example4.go](Go/day11_example4.go)
|
||||
Usando `%v` tendremos un valor por defecto, pero hay otras opciones que se pueden encontrar en la [documentación del paquete fmt](https://pkg.go.dev/fmt).
|
||||
|
||||
Variables may also be defined in a simpler format in your code. Instead of defining that it is a `var` and the `type` you can code this as follows to get the same functionality but a nice cleaner and simpler look for your code. This will only work for variables though and not constants.
|
||||
Se pone interesante la cosa, puedes ver el código de ejemplo [day11_example4.go](Go/day11_example4.go)
|
||||
|
||||
Las variables también pueden ser definidas en un formato más simple aun. En vez de definir `var` y el "tipo" puedes codificarla de la siguiente manera para obtener la misma funcionalidad pero con un aspecto más limpio y sencillo. Esto sólo funcionará para las variables y no para las constantes.
|
||||
|
||||
```
|
||||
func main() {
|
||||
@ -103,55 +105,53 @@ func main() {
|
||||
const daystotal = 90
|
||||
```
|
||||
|
||||
## Data Types
|
||||
## Tipos de datos
|
||||
|
||||
In the above examples, we have not defined the type of variables, this is because we can give it a value here and Go is smart enough to know what that type is or at least can infer what it is based on the value you have stored. However, if we want a user to input this will require a specific type.
|
||||
En los ejemplos anteriores, no hemos definido el tipo de las variables, esto es porque podemos darle un valor y Go es lo suficientemente inteligente como para saber de qué tipo se trata o al menos puede inferir cuál es en base al valor que ha almacenado. Sin embargo, si queremos que un usuario ingrese esto requerirá un tipo específico.
|
||||
|
||||
We have used Strings and Integers in our code so far. Integers for the number of days and strings are for the name of the challenge.
|
||||
Hasta ahora hemos utilizado Strings y Integers en nuestro código. Los integer para el número de días y los strings para el nombre del reto.
|
||||
|
||||
It is also important to note that each data type can do different things and behaves differently. For example, integers can multiply where strings do not.
|
||||
Es importante tener en cuenta que cada tipo de datos puede hacer cosas diferentes y se comporta de forma distinta. Por ejemplo, los integer pueden multiplicarse mientras que las cadenas no.
|
||||
|
||||
There are four categories
|
||||
Hay cuatro categorías:
|
||||
|
||||
- **Basic type**: Numbers, strings, and booleans come under this category.
|
||||
- **Aggregate type**: Array and structs come under this category.
|
||||
- **Reference type**: Pointers, slices, maps, functions, and channels come under this category.
|
||||
- **Tipo Basic**: Los números, las cadenas y los booleanos entran en esta categoría.
|
||||
- **Tipo Aggregate**: Los arrays y los structs entran en esta categoría.
|
||||
- **Tipo Reference**: Pointers, slices, maps, functions, y channels se incluyen en esta categoría.
|
||||
- **Interface type**
|
||||
|
||||
The data type is an important concept in programming. Data type specifies the size and type of variable values.
|
||||
El tipo de datos es un concepto importante en la programación, pues especifica el tamaño y el tipo de los valores de las variables.
|
||||
|
||||
Go is statically typed, meaning that once a variable type is defined, it can only store data of that type.
|
||||
Go está tipado estáticamente, lo que significa que una vez que se define un tipo de variable, sólo puede almacenar datos de ese tipo.
|
||||
|
||||
Go has three basic data types:
|
||||
Go tiene tres tipos de datos básicos:
|
||||
|
||||
- **bool**: represents a boolean value and is either true or false
|
||||
- **Numeric**: represents integer types, floating-point values, and complex types
|
||||
- **string**: represents a string value
|
||||
- **bool**: representa un valor booleano, es verdadero o falso
|
||||
- **Numeric**: representa tipos integer, valores de punto float y tipos complejos.
|
||||
- **string**: representa un valor de cadena
|
||||
|
||||
I found this resource super detailed on data types [Golang by example](https://golangbyexample.com/all-data-types-in-golang-with-examples/)
|
||||
Este recurso está súper detallado sobre los tipos de datos: [Golang by example](https://golangbyexample.com/all-data-types-in-golang-with-examples/).
|
||||
|
||||
I would also suggest [Techworld with Nana](https://www.youtube.com/watch?v=yyUHQIec83I&t=2023s) at this point covers in detail a lot about the data types in Go.
|
||||
|
||||
If we need to define a type in our variable we can do this like so:
|
||||
Si necesitamos definir un tipo en nuestra variable podemos hacerlo así:
|
||||
|
||||
```
|
||||
var TwitterHandle string
|
||||
var DaysCompleted uint
|
||||
```
|
||||
|
||||
Because Go implies variables where a value is given we can print out those values with the following:
|
||||
Como Go implica variables donde se da un valor podemos imprimir esos valores con lo siguiente:
|
||||
|
||||
```
|
||||
fmt.Printf("challenge is %T, daystotal is %T, dayscomplete is %T\n", conference, daystotal, dayscomplete)
|
||||
```
|
||||
|
||||
There are many different types of integer and float types the links above will cover these in detail.
|
||||
Hay muchos tipos diferentes de integer y floats.
|
||||
|
||||
- **int** = whole numbers
|
||||
- **unint** = positive whole numbers
|
||||
- **floating point types** = numbers that contain a decimal component
|
||||
- **int** = números enteros
|
||||
- **unint** = números enteros positivos
|
||||
- **floating point types** = números que contienen un componente decimal
|
||||
|
||||
## Resources
|
||||
## Recursos
|
||||
|
||||
- [StackOverflow 2021 Developer Survey](https://insights.stackoverflow.com/survey/2021)
|
||||
- [Why we are choosing Golang to learn](https://www.youtube.com/watch?v=7pLqIIAqZD4&t=9s)
|
||||
@ -161,6 +161,6 @@ There are many different types of integer and float types the links above will c
|
||||
- [FreeCodeCamp - Learn Go Programming - Golang Tutorial for Beginners](https://www.youtube.com/watch?v=YS4e4q9oBaU&t=1025s)
|
||||
- [Hitesh Choudhary - Complete playlist](https://www.youtube.com/playlist?list=PLRAV69dS1uWSR89FRQGZ6q9BR2b44Tr9N)
|
||||
|
||||
Next up we are going to start adding some user input functionality to our program so that we are asked how many days have been completed.
|
||||
En el próximo día vamos a empezar a añadir alguna funcionalidad de entrada, para que el usuario pueda añadir datos en nuestro programa, por ejemplo, los días que se han completado.
|
||||
|
||||
See you on [Day 12](day12.md).
|
||||
Nos vemos en el [Día 12](day12.md).
|
||||
|
Loading…
Reference in New Issue
Block a user