Blog de programación, errores, soluciones

Chose Language:
Author: Admin/Publisher |not checked

Sintaxis en el lenguaje GO

En un principio tuve cierta duda de si crear esta entrada, pero cambie de ida y creo que es necesario dar un ejemplo de como se ve la sintaxis en el lenguaje GO sin ser en un ejemplo simple tal y como vemos en otras páginas.

El ejemplo de sintaxis que nos da la página de golang.org es el siguiente:

package main

import "fmt"

func main() {
	fmt.Println("Hello, 世界")
}
Hello, 世界

Pero que vemos en este ejemplo, que es lo importante aqui?

Package Main y func Main

Como podemos ver tenemos la primera sentencia package main esto indica a qué paquete pertenece este archivo, luego de esta sentencia tenemos un import para poder usar la librería de formato import «fmt». Y de último tenemos a la función main func main el nombre de esta función no es cualquier nombre.

Nuestros programas empiezan en la función main, esta es la función que ejecutara desde el inicio en nuestro package main.

Hora de un ejemplo más complejo en GO

A la hora de decidirte a estudiar GO lo mejor es ver si la forma de escribir un programa te atrae, ¿te va a ser fácil comprender o no? Y créeme GO es probablemente el lenguaje más fácil de leer que me he topado hasta ahora habiendo estudiado, PHP, Python, algo de java en mis inicios, también he visto algo de C# y otros más y por último GO.

Si eres programador, probablemente entenderás con facilidad lo del siguiente código.

// Example by blastcoding.com
package main
import (
	"bufio"
	"fmt"
	"os"
	"regexp"
	"runtime"
	"strconv"
	"strings"
)
type Person struct {
	name      string
	surname   string
	telephone int
	iDocument int
	birthday  string
	picture   string
	email     string
}
var colorYellow string = ""
var colorBlue string = ""
var crlf string = ""
func main() {
	actualAsk := 1
	switch os := runtime.GOOS; os {
	case "darwin", "linux":
		colorYellow = "\033[33m"
		colorBlue = "\033[34m"
		crlf = "\n"
	default:
		colorYellow = ""
		colorBlue = ""
		crlf = "\r\n"
	}
	user := Person{
		name:      "",
		surname:   "",
		telephone: 0,
		iDocument: 0,
		birthday:  "",
		picture:   "",
	}
	for true {
		showMenu(colorBlue)
		response := callAsk(actualAsk, user)
		/*response := askName(colorYellow)*/
		response = strings.TrimRight(response, crlf)
		switch response {
		case ":end":
			os.Exit(3)
		case ":help":
			showHelp(colorYellow)
		case ":show":
			showUserInfo(colorYellow, user)
		case ":back":
			actualAsk -= 1
		case ":next":
			if actualAsk == 7 {
				showUserInfo(colorYellow, user)
			}
			actualAsk += 1
		case ":to 1":
			actualAsk = 1
		case ":to 2":
			actualAsk = 2
		case ":to 3":
			actualAsk = 3
		case ":to 4":
			actualAsk = 4
		case ":to 5":
			actualAsk = 5
		case ":to 6":
			actualAsk = 6
		case ":to 7":
			actualAsk = 7
		default:
			pcheck := proccessAsk(actualAsk, &user, response)
			if pcheck {
				if actualAsk < 8 {
					actualAsk = actualAsk + 1
					fmt.Println(string(colorYellow), "continue")
				} else {
					showUserInfo(colorYellow, user)
				}
			}
			fmt.Println(string(colorYellow), "repeat ask"+strconv.FormatBool(pcheck))
		}
	}
}
func proccessAsk(actualAsk int, user *Person, response string) bool {
	var check bool = true
	switch actualAsk {
	case 1: //name
		check, _ = regexp.MatchString("([a-zA-Z]){2,}", response)
		if check {
			user.name = response
		} else {
			fmt.Println(string(colorYellow), "Please re-enter name")
		}
	case 2: //surname
		check, _ = regexp.MatchString("([a-zA-Z]){1,}", response)
		if check {
			user.surname = response
		} else {
			fmt.Println(string(colorYellow), "Please re-enter surname")
		}
	case 3: //telephone
		check, _ = regexp.MatchString("([0-9]){8,9}", response)
		if check {
			processed_response, _ := strconv.Atoi(response)
			user.telephone = processed_response
		} else {
			fmt.Println(string(colorYellow), "the number that you try to enter is not valid plaese re enter it")
		}
	case 4: //iDocument
		check, _ = regexp.MatchString("([0-9]){8,}", response)
		if check {
			processed_response, _ := strconv.Atoi(response)
			user.iDocument = processed_response
		} else {
			fmt.Println(string(colorYellow), "the number that you try to enter is not valid plaese re enter it")
		}
	case 5: //birthday
		check, _ = regexp.MatchString("([0-2][0-9]|(3)[0-1])(\\/)(((0)[0-9])|((1)[0-2]))(\\/)\\d{4}", response)
		if check {
			user.birthday = response
		} else {
			fmt.Println(string(colorYellow), "that' s not a valid date")
		}
	case 6: //picture
		user.picture = strconv.Itoa(user.iDocument) + ".jpg"
	case 7: //email
		check, _ = regexp.MatchString("[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}", response)
		if check {
			user.email = response
		} else {
			fmt.Println(string(colorYellow), "email entered is incorrect:")
		}
	}
	return check
}
func callAsk(actualAsk int, user Person) string {
	var xresponse string
	switch actualAsk {
	case 1:
		xresponse = askName(colorYellow)
	case 2:
		xresponse = askSurname(colorYellow)
	case 3:
		xresponse = askTelephone(colorYellow)
	case 4:
		xresponse = askIDocument(colorYellow)
	case 5:
		xresponse = askBirthday(colorYellow)
	case 6:
		xresponse = askPicture(colorYellow)
	case 7:
		xresponse = askEmail(colorYellow)
	case 8:
		showUserInfo(colorYellow, user)
		reader := bufio.NewReader(os.Stdin)
		xresponse, _ = reader.ReadString('\n')
	}
	return xresponse
}
func showMenu(colorBlue string) {
	/*reader := bufio.NewReader(os.Stdin)*/
	fmt.Println(string(colorBlue), "you can use the following commands [back][next][end][help]")
	/*name, _ := reader.ReadString('\n')
	return name*/
}
func showHelp(colorYellow string) {
	message := "[back] send you back to the last instance \n-\n"
	message += "[to] go to question, posible values 1,2,3,4,5,6\n"
	message += "where these are the questions:\n"
	message += "1: name, 2:surname, 3:telephone, 4:CI or DNI, 5:birthday, 6:picture, 7:email\n-\n"
	message += "Example [to 1]\n-\n"
	message += "[next] go next ask\n-\n"
	message += "[end] close the program\n-\n"
	message += "you are in help command =D\n-\n"
	fmt.Println(string(colorYellow), message)
}
func showUserInfo(colorYellow string, user Person) {
	message := "=================================\n\n"
	message += "The user information is:\n"
	message += "Name:" + user.name + "\n"
	message += "Surname:" + user.surname + "\n"
	message += "Telephone:" + strconv.Itoa(user.telephone) + "\n"
	message += "CI:" + strconv.Itoa(user.iDocument) + "\n"
	message += "Birthday:" + user.birthday + "\n"
	/*message += "Picture:" + user.iDocument + "\n"*/
	message += "=================================\n\n"
	message += "Opening Picture"
	fmt.Println(string(colorYellow), message)
}
func askName(colorYellow string) string {
	reader := bufio.NewReader(os.Stdin)
	fmt.Println(string(colorYellow), "dime tu nombre")
	name, _ := reader.ReadString('\n')
	return name
}
func askSurname(colorYellow string) string {
	reader := bufio.NewReader(os.Stdin)
	fmt.Println(string(colorYellow), "[EN]Surname:,[ES]Apellido:")
	surname, _ := reader.ReadString('\n')
	return surname
}
func askTelephone(colorYellow string) string {
	reader := bufio.NewReader(os.Stdin)
	fmt.Println(string(colorYellow), "[EN]:Telephone, [ES]Telefono:")
	telephone, _ := reader.ReadString('\n')
	return telephone
}
func askIDocument(colorYellow string) string {
	reader := bufio.NewReader(os.Stdin)
	fmt.Println(string(colorYellow), "[EN]:DNI,[ES]CI,DNI:")
	iDocument, _ := reader.ReadString('\n')
	return iDocument
}
func askBirthday(colorYellow string) string {
	reader := bufio.NewReader(os.Stdin)
	fmt.Println(string(colorYellow), "[EN]:Birthday,[ES]Fecha de Nacimiento:")
	birthday, _ := reader.ReadString('\n')
	return birthday
}
func askPicture(colorYellow string) string {
	reader := bufio.NewReader(os.Stdin)
	fmt.Println(string(colorYellow), "[EN]:Picture,[ES]Foto:")
	picture, _ := reader.ReadString('\n')
	return picture
}
func askEmail(colorYellow string) string {
	reader := bufio.NewReader(os.Stdin)
	fmt.Println(string(colorYellow), "Email")
	email, _ := reader.ReadString('\n')
	return email
}

Bueno talvez para un ejemplo de sintaxis talvez se me fue la mano, pero si vienes de otro lenguaje y miras un poco de que pasa aquí te darás cuenta fácilmente lo que está pasando.

Solo no te dejes intimidar por la cantidad de código. Exponer a alguien que está comenzando a una gran cantidad de código es lo mejor que se puede hacer a mi parecer en programación. Después de todo tarde o temprano manejarás volúmenes como estos tarde o temprano.

Si te preguntas el como se vería este código en un editor de texto sería algo así:

go syntaxis on ATOM

Category: go
Something wrong? If you found an error or mistake in the content you can contact me on Twitter | @luisg2249_luis.
Last 4 post in same category