Logic

지니🧸·2023년 8월 29일
0

Go

목록 보기
4/8

본 게시글은 Golang Tutorial for Beginners | Full Go Course을 학습하며 작성한 개인 노트입니다.

Loops

For

an indefinite loop

for {
	// code
}

Conditional for loop

	// code

For each

firstNames := []string{}
for _, booking := range bookings {
	var names = strings.Fields(booking)
	firstNames = append(firstNames, names[0])
}

Range

  • iterates over elements for different data structures
  • provides index and value for each element

Split strings

strings.Fields(string value)

splits the string with white space as separator & returns a slice with split elements

Blank identifier

_

  • to ignore a variable you don't want to use
  • if a variable is named & not used, Go gives you an error

If else statements

if remainingTickets == 0 {
	// end program
	fmt.Println("Our conference is booked out. Come back next year.")
	break // ends the loop
}
if userTickets > int(remainingTickets) {
	fmt.Printf("We only have %v tickets remaining, so you can't book %v tickets\n", remainingTickets, userTickets)
	continue
}

if - else if - else

  • only one if and else possible

User input validation

First/last name is longer than two characters

var isValidName bool = len(firstName) >= 2 && len(lastName) >= 2

Email includes @

isValidEmail := strings.Contains(email, "@")

Switch

  • allows a variable to be tested for different conditions
  • default - if none of the specificed conditions are true
city := "London"
switch city {
	case "New York": 
    	// code
    case "Singapore":
    	//code
	default:
    	// code
}
profile
우당탕탕

0개의 댓글