No tienes acceso a esta clase

¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera

Structs y Receivers

10/42
Recursos

Aportes 28

Preguntas 2

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad?

Di solución con expresiones regulares para validar la entrada y obtener los datos. Aplicando todo lo que aprendí en este gran curso de Expresiones Regulares.

func main() {
	fmt.Println("Type an operation (e.g 2+2, 5*5, 8-9, 7/8)")
	regex := regexp.MustCompile(`^(\d+)([\+\-\*\/])(\d+)$`)
	input := readInput()
	fmt.Println()
	if regex.Match([]byte(input)) {
		c := calc{}
		valueone := parse(regex.ReplaceAllString(input, "$1"))
		operation := regex.ReplaceAllString(input, "$2")
		valuetwo := parse(regex.ReplaceAllString(input, "$3"))
		fmt.Println(c.operate(valueone, operation, valuetwo))
		} else {
		fmt.Println("The input is not valid")
	}
}

Struct: tipo de dato que tu mismo creas, el cual puedes agregar métodos y propiedades.

type nombre struct{}

Funcionan como formularios en papel que podría usar.
Recogen diferentes datos y los organizan con diferentes nombres de campos. Cuando inicia una variable con una nueva struct, es como si fotocopiase un formulario y lo dejase listo para completarse.

Las Receiver Function le da la propiedad al struct de tener el método dentro de el, es decir cuando instanciemos a la struct vamos a poder llamar a los métodos dentro de la Receiver Function.

func (nombre struct) nombrefunción (variable string) int{}

referencia : https://www.digitalocean.com/community/tutorials/defining-structs-in-go-es

Comparto mi versión de la calculadora:

https://github.com/cristian-rincon/gocalculatorcli

El proyecto utilizando entradas de la consola

package main

import "os"
import "fmt"
import "strconv"

func parse(str string) int {
	value, err := strconv.Atoi(str)
	if err != nil {
		fmt.Println("Error: format: int '<operator>' int")
		os.Exit(1)
	}
	return value
}

type calc struct {
	intA     int
	intB     int
	operator string
}

func (self calc) operate() *int {

	total := 0

	switch self.operator {
	case "+":
		total = self.intA + self.intB
	case "-":
		total = self.intA - self.intB
	case "*":
		total = self.intA * self.intB
	case "/":
		total = self.intA / self.intB
	}

	return &total
}

func main() {

	if len(os.Args) != 4 {
		fmt.Println("Error: format: int '<operator>' int")
		os.Exit(1)
	}

	instance := calc{
		intA:     parse(os.Args[1]),
		intB:     parse(os.Args[3]),
		operator: os.Args[2],
	}

	response := instance.operate()
	if response == nil {
		fmt.Println("Only '+', '-', '*' and '/' operators are allowed")
		os.Exit(1)
	}

	fmt.Println(*response)
}

Holas, aquí les comparto el código que básicamente tiene la misma funcionalidad, pero con la diferencia de que el usuario puede digitar una cantidad n de operandos, dichos son guardados y procesados mediante el uso de slices.

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

type Calculator struct {
	operators []int
	operation string
	result    int
}

func newCalculator(operators []int, operation string) *Calculator {
	return &Calculator{
		operators: operators,
		operation: operation,
		result:    0,
	}
}

func (c *Calculator) add(num int) {
	c.operators = append(c.operators, num)
}

func (c *Calculator) subtract(num int) {
	c.operators = append(c.operators, -num)
}

func (c *Calculator) multiply() {
	c.result = c.operators[0]
	for i := 1; i < len(c.operators); i++ {
		c.result *= c.operators[i]
	}
}

func (c *Calculator) divide() {
	c.result = c.operators[0]
	for i := 1; i < len(c.operators); i++ {
		c.result /= c.operators[i]
	}
}

func (c *Calculator) sum() {
	for _, v := range c.operators {
		c.result += v
	}
}

func (c *Calculator) rest() {
	c.result = c.operators[0]

	for i := 1; i < len(c.operators); i++ {
		c.result -= c.operators[i]
	}

}

func (c *Calculator) print() {

	fmt.Printf("El resultado de la operación %s es: %d", c.operation, c.result)
}

func parserEntry(entrada string) int {
	valoresParseados, err := strconv.Atoi(entrada)
	if err != nil {
		fmt.Println("Error al convertir el valor")
	}
	return valoresParseados
}

func (c Calculator) calculatorHanlder() {

	switch c.operation {
	case "+":
		c.operation = "Suma"
		c.sum()
		c.print()
		break
	case "-":
		c.operation = "Resta"
		c.rest()
		c.print()
		break
	case "*":
		c.operation = "Multiplicación"
		c.multiply()
		c.print()
		break
	case "/":
		c.operation = "División"
		c.divide()
		c.print()
		break
	default:
		fmt.Println("Operador no reconocido")
		c.result = 0
		break
	}
}

func readEntry() string {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	valores := scanner.Text()
	return valores
}

func converToInt(sliceString []string) []int {
	var sliceInt []int
	for _, v := range sliceString {
		valoresParseados, err := strconv.Atoi(v)
		if err != nil {
			fmt.Println("Error al convertir el valor")
		}
		sliceInt = append(sliceInt, valoresParseados)
	}
	return sliceInt
}

func main() {

	fmt.Println("Digita los números que quieres operar")
	entry := readEntry()
	fmt.Println("Digita el operador que quieres usar")
	operator := readEntry()
	operators := strings.Split(entry, operator)
	operatorsInt := converToInt(operators)

	calculator := newCalculator(operatorsInt, operator)

	calculator.calculatorHanlder()
}

El código de la clase con comentarios y una pequeña mejora en la experiencia de usuario:

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

// Función que nos permite leer la entrada del usuario y devolver el valor que ha introducido
func readInput() string {
	// Lee la entrada de un usaurio
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()

	// Devuelve el valor introducido por el usuario
	return scanner.Text()
}

// Función que nos permite recibir un string, transformarlo en un int y devolverlo
func parsear(input string) int {
	// Transformamos los strings en valores de tipo int
	operator, err := strconv.Atoi(input)
	if err != nil { // Manejando el error al parsear los datos de string a int
		fmt.Println(err)
	}

	// Devuelve en valor de tipo int
	return operator
}

/*
	STRUCT
*/
type calc struct{}

// Metodo del STRUCT
func (calc) operate(operators string, symbol string) int {
	// Convierte en una lista los valores que reciba en "operators" separados por el valor "symbol". Ejm: Recibe 2+2, lo transforma en [2 2]
	inputSplit := strings.Split(operators, symbol)

	// Parsea los strigns de la lista para recibir int
	operator1 := parsear(inputSplit[0])
	operator2 := parsear(inputSplit[1])

	// Evalúa el símbolo recibido para realizar la operación correspondiente
	switch symbol {
	case "+":
		// SUMA
		return operator1 + operator2
	case "-":
		// RESTA
		return operator1 - operator2
	case "*":
		// Multiplicación
		return operator1 * operator2
	case "/":
		// División
		return operator1 / operator2
	default:
		fmt.Println("El operador indicado no es correcto o no está soportado") // Muestra el mensaje por defecto
		return 0
	}
}

func main() {
	fmt.Println("Introduzca los valores que quiere calcular:")
	operators := readInput()
	fmt.Println("Introduzca el símbolo de la operación aritmética que quiere realizar:")
	symbol := readInput()

	// Instanciamos el Struct
	c := calc{}
	// Llamamos al método "operate" del Struct para realizar la operación que deseamos
	result := c.operate(operators, symbol)

	// Devolvemos el resultado de la operación
	fmt.Println("El resultado de la operación es:")
	fmt.Println(result)
}

Aplique varias structs y lo aprendido en el curso de go intermedio sobre constructores y apuntadores:

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

type operation struct {
	v1 int
	v2 int
	operator string
}

type calc struct {}

type std struct {}

func (std) in(scanner *bufio.Scanner) string {
	scanner.Scan()
	return scanner.Text()
}

func (self calc) calculate(unparsedOperation string, arithmeticOperator string) (int, error) {

	operation, err := self.parse(unparsedOperation, arithmeticOperator)

	if err != nil {
		return 0, err
	}

	v1 := *&operation.v1
	v2 := *&operation.v2

	switch arithmeticOperator {
	case "+":
		return (v1 + v2), nil
	case "-":
		return (v1 - v2), nil
	case "*":
		return (v1 * v2), nil
	case "/":
		return (v1 / v2), nil
	default:
		return 0, fmt.Errorf("The operator %s is not supported\n", arithmeticOperator)
	}
}


func (calc) parse(unparsedOperation string, arithmeticOperator string) (*operation, error) {
	values := strings.Split(unparsedOperation, arithmeticOperator)
	v1, err1 := strconv.Atoi(values[0])
	v2, err2 := strconv.Atoi(values[1])

	if (err1 == nil && err2 == nil) {
		return &operation{
			v1: v1,
			v2: v2,
			operator: arithmeticOperator,
		}, nil
	} else {
		return nil, fmt.Errorf("Error: parser failed to parse stdin.")
	}
}

func main() {

	scanner := bufio.NewScanner(os.Stdin)
	std := std{}
	var arithmeticOperator string

	fmt.Printf("Operation: ")
	operation := std.in(scanner)

	fmt.Printf("Type operation: ")
	arithmeticOperator = std.in(scanner)

	calculator := calc{}
	
	ret, err := calculator.calculate(operation, arithmeticOperator)

	if err != nil {
		panic(err)
	}

	fmt.Printf("\nThe answer is: %d\n", ret)
}

package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"strconv"
	"strings"
)

type calc struct{}

func (calc) parseString(operator string) (int, error) {
	result, err := strconv.Atoi(operator)
	return result, err
}

func (c calc) operate(input string, operation string) (int, error) {
	cleanInput := strings.Split(input, operation)
	first, err := c.parseString(cleanInput[0])
	if err != nil {
		return 0, err
	}
	second, err := c.parseString(cleanInput[1])
	if err != nil {
		return 0, err
	}

	switch operation {
	case "+":
		return first + second, nil
	case "-":
		return first - second, nil
	case "*":
		return first * second, nil
	case "/":
		return first / second, nil
	default:
		log.Println(operation, "operation is not supported!")
		return 0, nil

	}

}

func main() {
	fmt.Println("Enter your input")
	input := readInput()
	fmt.Println("Enter your operation")
	operator := readInput()
	processResult(input, operator)

}

func readInput() string {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	return scanner.Text()
}

func processResult(input string, operator string) {
	c := calc{}
	value, err := c.operate(input, operator)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println("Result of", input, "equals to", value)
	}
}

Encontrando el operador y los operandos usando ExpReg:


	regex := regexp.MustCompile(`^(\d+)([\+\-\*\/])(\d+)$`)
	res := regex.FindStringSubmatch(operacion)
	operador := res[2]
	operando1,_ := strconv.Atoi(res[1])
	operando2,_ := strconv.Atoi(res[3])

Yo implementé esa solución con la función “strings.Cut()” para poder usar cualquiera de los 4 operadores validos

	// creating an array with the allowed operators
	allowedOperators := [4]string{"+", "-", "*", "/"}

	var number1 float64
	var number2 float64
	var operator string
	// verifing if a valid operator is used in the string operation
	for _, validOperator := range allowedOperators {
		// We need to convert the strings to numbers
		before, after, found := strings.Cut(operation, validOperator)

		if found == true {
			var err error
			number1, err = strconv.ParseFloat(before, 0)
			if err != nil {
				log.Fatal(err)
			}

			number2, err = strconv.ParseFloat(after, 0)
			if err != nil {
				log.Fatal(err)
			}

			operator = validOperator
			break
		} else {
			operator = "invalid"
		}
	}
package main

import (
	"bufio"
	"errors"
	"fmt"
	"os"
	"regexp"
	"strconv"
)

type calc struct{}

func (calc) operate(in1, in2 int, operation string) (result int, err error) {
	switch operation {

	case "+":
		result = in1 + in2

	case "-":
		result = in1 - in2

	case "*":
		result = in1 * in2

	case "/":
		result = in1 / in2

	default:
		err = errors.New("no operation executed!")

	}

	return
}

func parseInt(userInput string) int {
	value, _ := strconv.Atoi(userInput)
	return value
}

func readInput() string {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()

	return scanner.Text()
}

func parseInput(input string) (in1, in2 int, operation string, err error) {
	regex := regexp.MustCompile(`^(\d+)([\+\-\*\/])(\d+)$`)

	if regex.Match([]byte(input)) {
		in1 = parseInt(regex.ReplaceAllString(input, "$1"))
		in2 = parseInt(regex.ReplaceAllString(input, "$3"))
		operation = regex.ReplaceAllString(input, "$2")
	} else {
		err = errors.New("data is not valid")
	}

	return
}

func main() {
	fmt.Println("Type an operation (e.g 2+2, 5*5, 8-9, 7/8)")

	in1, in2, operation, err := parseInput(readInput())

	if err != nil {
		fmt.Println(err)
		return
	}

	c := calc{}
	result, err := c.operate(in1, in2, operation)

	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println("Result: ", result)
}

Por fin entendí que es eso de los receivers, grfacias

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

type calc struct {
}

func (calc) operate(entrada string, operador string) int {
	datos := strings.Split(entrada, operador)
	operador1 := parsear(datos[0])
	operador2 := parsear(datos[1])
	switch operador {
	case "+":
		fmt.Println(operador1 + operador2)
		return operador1 + operador2
	case "-":
		fmt.Println(operador1 - operador2)
		return operador1 - operador2
	case "*":
		fmt.Println(operador1 * operador2)
		return operador1 * operador2
	case "/":
		fmt.Println(operador1 / operador2)
		return operador1 / operador2
	default:
		return 0
	}
}
func entrada() string {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	return scanner.Text()
}

func parsear(texto string) int {
	operador, _ := strconv.Atoi(texto)
	return operador
}
func main() {
	c := calc{}
	entradaDatos := entrada()
	operador := entrada()

	c.operate(entradaDatos, operador)

}

Hola!,

Por medio de expresiones regulares valido que la operación a realizar sea valida y adicionalmente, según el tipo de operador al tomarlo de la expresión regular, se realiza el calculo matametico.

package main

import (
	"bufio"
	"errors"
	"fmt"
	"os"
	"regexp"
	"strconv"
)

type calc struct {}

func (c *calc) Operate(in string) (*int, error) {
	reg := regexp.MustCompile(`^(\d+)([+\-*/])(\d+)$`)
	values := reg.FindAllStringSubmatch(in, -1)

	if len(values) == 0 {
		return nil, errors.New("the math operation entered is not valid")
	}

	result := c.operationProcess(values[0][2], c.parseToInt(values[0][1]), c.parseToInt(values[0][3]))

	return &result, nil
}

func (c *calc) parseToInt(num string) int {
	conNum, _ := strconv.Atoi(num)
	return conNum
}

func (c *calc) operationProcess(operator string, operating1 int, operating2 int) int {
	var result int

	switch operator {
	case "+":
		result = operating1 + operating2
	case "-":
		result = operating1 - operating2
	case "*":
		result = operating1 * operating2
	case "/":
		result = operating1 / operating2
	}

	return result
}

func main() {
	fmt.Println("Type the basic math operation to calculate")

	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	operation := scanner.Text()

	calculator := calc{}
	result, err := calculator.Operate(operation)

	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println("the result of the operation is:", *result)
}

Interesante… Buena clase

Aca mi ejercicio

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

type calculate struct {
}

func (calculate) operate(numberOne int, numberTwo int, operation string) int {
	switch operation {
	case "+":
		fmt.Println(numberOne + numberTwo)
		return numberOne + numberTwo
	case "-":
		fmt.Println(numberOne - numberTwo)
		return numberOne - numberTwo
	case "*":
		fmt.Println(numberOne * numberTwo)
		return numberOne * numberTwo
	case "/":
		fmt.Println(numberOne / numberTwo)
		return numberOne / numberTwo
	default:
		fmt.Println("Wrong Operation.")
		return 0
	}
}

func readInput(message string) string {
	fmt.Println(message)
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	data := scanner.Text()
	return data
}

func main() {

	data := readInput("Insert the operation ej: 2+2): ")
	operator := readInput("Insert a operator symbol.")
	numbers := strings.Split(data, operator)

	numberOne, _ := strconv.Atoi(numbers[0])
	numberTwo, _ := strconv.Atoi(numbers[1])

	var cal calculate
	cal.operate(numberOne, numberTwo, operator)
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"regexp"
	"strconv"
)

type calc struct {
	e1 int
	e2 int
}

func (self calc) operate(operador string) int {
	operador1 := self.e1
	operador2 := self.e2

	var resultado int

	switch operador {
	case "+":
		resultado = operador1 + operador2
	case "-":
		resultado = operador1 - operador2
	case "*":
		resultado = operador1 * operador2
	case "/":
		if operador2 == 0{
			fmt.Println("Error: Division entre cero")
			return 0
		}
		resultado = operador1 / operador2
	default:
		fmt.Println("Operador no aceptado")
		resultado = 0
	}

	return resultado
}

func parsear(entrada string) int {
	operador, _ := strconv.Atoi(entrada)
	return operador
}

func leerEntrada() string {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()

	return scanner.Text()
}

func main() {
	regex := regexp.MustCompile(`^(\d+)([\+\-\*\/])(\d+)$`)

	entrada := leerEntrada()

	if regex.Match([]byte(entrada)) {
		entrada1 := parsear(regex.ReplaceAllString(entrada, "$1"))
		operador := regex.ReplaceAllString(entrada, "$2")
		entrada2 := parsear(regex.ReplaceAllString(entrada, "$3"))

		c := calc{e1: entrada1, e2: entrada2}
		toPrint := c.operate(operador)

		fmt.Println(toPrint)
	}

}

asi quedo:

package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
	"strconv"
)

type calc struct{}

func (calc) operate(entrada string, operador string) int {
	entradaLipia := strings.Split(entrada, operador)
	operador1 := parsear(entradaLipia[0])
	operador2 := parsear(entradaLipia[1])
	switch operador {
	case "+":
		fmt.Println(operador1 + operador2)
		return operador1 + operador2
	case "-":
		fmt.Println(operador1 - operador2)
		return operador1 - operador2
	case "*":
		fmt.Println(operador1 * operador2)
		return operador1 * operador2
	case "/":
		if operador2 == 0 {
			fmt.Println("no se puede dividir por 0")
			return 0
		} else {
			fmt.Println(operador1 / operador2)
			return operador1 / operador2
		}
	default:
		fmt.Println("el operador->", operador, "no esta soportado")
		return 0
	}
}

func parsear(entrada string) int {
	operador, _ := strconv.Atoi(entrada)
	return operador
}

func leerEntrada() string {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	return scanner.Text()
}

func main()  {
	entrada := leerEntrada()
	operador := leerEntrada()
	c := calc{}
	fmt.Println(c.operate(entrada, operador))
}

Dejo mi version de calculadora. Uso expresiones regulares para obtener la operacion y booleanos para errores. El resto es parecido a lo hecho en el curso. Documentacion: https://golang.org/pkg/regexp/#Regexp.FindString

package main

import (
	"bufio"
	"fmt"
	"os"
	"regexp"
	"strconv"
	"strings"
)

type calculadora struct{}

func (calculadora) calcular(operandoUno int, operandoDos int, operacion string) int {
	resultado := 0
	switch operacion {
	case "+":
		resultado = operandoUno + operandoDos
	case "-":
		resultado = operandoUno - operandoDos
	case "*":
		resultado = operandoUno * operandoDos
	case "/":
		if operandoDos != 0 {
			resultado = operandoUno / operandoDos
		} else {
			fmt.Println("No se puede dividir por Cero.")
		}
	}
	return resultado
}

func obtenerExpresion() string {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	return scanner.Text()
}

func obtenerOperacion(expresion string) (string, bool) {
	operaciones := regexp.MustCompile(`[+,-,*,/]`)
	operacion := operaciones.FindString(expresion)
	operacionInvalida := operacion == ""
	return operacion, operacionInvalida
}

func obtenerValores(expresion string, operacion string) (int, int, bool) {
	operadandos := strings.Split(expresion, operacion)
	operandoUno, errUno := strconv.Atoi(operadandos[0])
	operandoDos, errDos := strconv.Atoi(operadandos[1])
	return operandoUno, operandoDos, errUno != nil || errDos != nil
}

func main() {
	expresion := obtenerExpresion()
	operacion, errOp := obtenerOperacion(expresion)
	if errOp {
		fmt.Println("Operacion invalida")
		return
	}
	operandoUno, operandoDos, errVal := obtenerValores(expresion, operacion)
	if errVal {
		fmt.Println("Operandos invalidos")
		return
	}
	c := calculadora{}
	fmt.Println(c.calcular(operandoUno, operandoDos, operacion))
}
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {
	readOperation()
}

func readOperation() {
	// Declarar Scannner para leer desde el Teclado
	scanner := bufio.NewScanner(os.Stdin)
	fmt.Println("Escribe la operacion que desees separada con espacios ej: 2 + 2")

	// Leer entrada del teclado
	scanner.Scan()

	// Fragmentar la entrada por espacios [" "]
	operation := strings.Split(scanner.Text(), " ")

	// Obtener los numeros(convertirdos a enteros) y operador
	num1 := parseStrToInt(operation[0])
	op := operation[1]
	num2 := parseStrToInt(operation[2])

	// Instanciar nuestro struct [Calculator]
	cal := Calculator{}

	// Enviar los elementos de la operacion para ser resuelta
	cal.ResultOperation(op, num1, num2)
}

// Funcion privada que conviente un string a int
func parseStrToInt(num string) int {

	//Conversion del string con manejo de errores
	num1, err := strconv.Atoi(num)

	//En caso de error retornar 0
	if err != nil {
		return 0
	}

	//Regresar el numero convertido
	return num1
}

// Creamos nuestro Struct [Calculator]
type Calculator struct{}

// Funcion Receiver publica que recibe un operador y dos numeros y resuleve la operacion
func (Calculator) ResultOperation(op string, num1 int, num2 int) {

	// Condicionamos nuestro operador
	switch op {
	case "+":
		// Hacer suma
		fmt.Println("El resultado de la suma es:", (num1 + num2))

	case "-":
		// Hacer resta
		fmt.Println("El resultado de la resta es:", (num1 - num2))
		break

	case "*":
		// Hacer multiplicacion
		fmt.Println("El resultado de la multiplicacion es:", (num1 * num2))
		break

	case "/":
		// Hacer division
		fmt.Println("El resultado de la division es:", (num1 / num2))
		break

	default:
		// Indicar que no es soportada la operacion
		fmt.Println("El operador:[", op, "]no esta soportado")
		break
	}
}```

Se podría decir que Structs son muy parecidos a una Clase en Programación Orientada a Objetos…

mi codigo utilizo una flag para saber si si fue operador pero creo que no es la manera más óptima, considero que si el int fuera un objeto se podría validar sin el flag.

<code>
package main

import (
	"bufio"
	"errors"
	"fmt"
	"os"
	"strconv"
	"strings"
)


func main(){
	fmt.Println("Porfavor digite la operación")
	entry := readEntry()
	fmt.Println("Porfavor digite el operador")
	operator := readEntry()
	fmt.Println(entry)
	fmt.Println(operator)


	cleanedEntry := strings.Split(entry,operator);
	value1 := parseToInt(cleanedEntry[0])
	value2 := parseToInt(cleanedEntry[1])
	c := calc{}
	result,errorReturned := c.Operate(value1, value2,operator)

	if(errorReturned != nil){
		fmt.Println(errorReturned)
		os.Exit(0)
	}else{
		fmt.Println("El resultado de la operación es: ", result )
	}


}


type calc struct{}

	
func (calc) Operate(operador1 int, operador2 int, operador string) (int, error) {


	var field int;
	 flag := false;
	
 	switch operador{
		case "+":
			field = operador1 +operador2
			flag = true;
		case "-":
			field = operador1 +operador2
			flag = true;
		case "*":
			field = operador1 +operador2
			flag = true;
		case "/":
			field = operador1 +operador2
			flag = true;
		default:
			fmt.Println(operador, "no esta soportado")
	}

	if(flag){
		return field,nil;
	}else{
		return field, errors.New("no se puede realizar la operación ")
	}
		
}


func readEntry() string{
	scanner := bufio.NewScanner((os.Stdin))
	scanner.Scan()
	return scanner.Text()
}


func parseToInt(entrada string) int{
  	value, error := strconv.Atoi(entrada)

  	if(error != nil){
		fmt.Println("No se puede realizar la conversión de la entrada :" , entrada)
		os.Exit(0)
  	}
	return value
}
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

type calc struct{}

func (calc) operate(input string, operator string) int {
	cleanInput := strings.Split(input, operator)
	operator1 := parsear(cleanInput[0])
	operator2 := parsear(cleanInput[1])
	switch operator {
	case "+":
		fmt.Println(operator1 + operator2)
		return operator1 + operator2
	case "-":
		fmt.Println(operator1 - operator2)
		return operator1 - operator2
	case "*":
		fmt.Println(operator1 * operator2)
		return operator1 * operator2
	case "/":
		fmt.Println(operator1 / operator2)
		return operator1 / operator2
	default:
		fmt.Println(operator, "is not supported")
		return 0
	}
}

func parsear(input string) int {
	operator, _ := strconv.Atoi(input)
	return operator
}

func readInput() string {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	return scanner.Text()
}

func main()  {
	input := readInput()
	operator := readInput()
	fmt.Println(input)
	fmt.Println(operator)
	c := calc{}
	fmt.Println(c.operate(input, operator))
}

Casualmente esta clase me recuerda demasiado a mis primeros semestres de ingenieria de sistemas, y con el famoso Java!
Jajajaja Comenten si les pasó igual.
Go me esta encantando totalmente, es lindo, bueno y su sintax es hermosa

type calc struct{}

func (calc) parseString(operator string) (int, error) {
	result, err := strconv.Atoi(operator)
	return result, err
}```

buen curso ,