Skip to content

Instantly share code, notes, and snippets.

@mknparreira
Last active August 12, 2021 22:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mknparreira/7a8c89b809fc1e90e7333497e1f5d603 to your computer and use it in GitHub Desktop.
Save mknparreira/7a8c89b809fc1e90e7333497e1f5d603 to your computer and use it in GitHub Desktop.
Golang | This is an simple exemple of Golang problem
package main

import (
	"fmt"
)

func main() {
	fmt.Println("Hello, playground")
	team := []string{"Marta", "Louis", "Andrew", "Carl"}
	bus := New(team)
	fmt.Printf("Bus:\n %#v\n", bus)
	bus.Drop("Louis")
	fmt.Printf("Bus:\n %#v\n", bus)
	fmt.Printf("Bus:\n %#v\n", team)
}

type TwilightBus struct {
	passengers []string
}

func New(passengers []string) *TwilightBus{
	bus := TwilightBus{}
	bus.passengers = passengers
	return &bus
}

func (bus *TwilightBus) Pick (name string) {
	bus.passengers = append(bus.passengers, name)
}

func find(slice []string, needle string) (int, bool) {
	for i, item := range slice{
     		if (item == needle) {
			return i, true
     		} 
  	}
	return -1, false 
}

//Remove item from slice, preserving their order
func remove(slice []string, i int) []string {
	copy(slice[i:], slice[i+1:])
	return slice[:len(slice)-1]
}

func (bus *TwilightBus) Drop(name string) {
	i, found := find(bus.passengers, name)
	if(found){
		bus.passengers = remove(bus.passengers, i)
	}
}


//Este código, além de estar duplicando o ultimo passageiro, remove o passageiro da lista original

//Veja o resultado quando corremos o código:

/*
Bus:
 &main.TwilightBus{passengers:[]string{"Marta", "Louis", "Andrew", "Carl"}}
Bus:
 &main.TwilightBus{passengers:[]string{"Marta", "Andrew", "Carl"}}
Bus:
 []string{"Marta", "Andrew", "Carl", "Carl"}

*/


/*
  Para resolver este problema, alteramos o método new de forma que passsengers seja copiado e não mais alterado. 
  Pois pense só. Não é correto manipular o slice de team pois ele pode ser utilizado para outros fins. 
  O que queremos é utilizar esses dados, não manipulá-los.
*/

func New(passengers []string) *TwilightBus {
	bus := TwilightBus{}
	bus.passengers = make([]string, len(passengers))
	copy(bus.passengers, passengers)
	return &bus
}
@mknparreira
Copy link
Author

See the code in Golang Playground: https://play.golang.org/p/QrlHRn89HnW

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment