Data types, Input

지니🧸·2023년 8월 29일
0

Go

목록 보기
3/8

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

Data types

  • String: textual data
  • Integer: numeric data

Go is a statically typed language

  • You need to tell Go Compiler the data type when declaring the variable
  • Type inference: But Go can infer the type when value is assigned
  • When you don't immediately assign a value upon declaration, you have to define the type
var userName string
var userTickets int

Type conversion

uint & int

remainingTickets -= uint(userTickets)

uint > string

strconv.FormatUint(uint64(uint-value), base)

Arrays & Slices

Commonly used data types to store a list of values

Arrays

  • fixed size
  • var variable_name = [size]variable_type
  • cannot mix stored data types
  • values can be added and removed in code

Empty array:

-var bookings = [50]string{}
-var bookings [50]string

Initialize with values:

var bookings = [50]string{"Jack", "Peter"}

Adding new elements

bookings[0] = "Nana"
bookings[10] = "Xavier"

length of array

len(arr)

array type

fmt.Print(arr) >> [50]string

Slices

  • dynamic in size
  • automatically expands upon new elements
  • abstraction of an array
  • can get sub-array of its own

Initialize

var bookings = []string{}

bookings := []string{}

Add elements

bookings = append(bookings, firstName+" "+lastName)

User Input

var userName string

fmt.Scan(&userName)

You have to use a pointer to scan user input properly. Without a pointer, Go will run the program without the user input.

Pass the reference (not the value) into the scan function so that the scan function can assign the user's value to the variable based on the memory address the pointer has.

Pointer: the address of a variable


References:
https://www.geeksforgeeks.org/data-types-in-go/

profile
우당탕탕

0개의 댓글

Powered by GraphCDN, the GraphQL CDN