본문 바로가기
언어/Go

go test sample study

by gun_poo 2022. 7. 21.
package main

import "fmt"


func plus(a, b int, name string) (int, string) {
	return a + b, name
}
func main() {
	result, name := plus(2, 2, "gunwoo")
	fmt.Println(result, name)
}
package main

import "fmt"


func plus(a ... int) (int) {
	var total int 
	// == total := 0
	for _, item := range a {
		total += item
	}
	return total
	//_ => 무시
	//index = int 
	//item => main, 2, 3, 4, 5,6,7
	//range는 반복가능한 것들을 반복하게 해준다
}
func main() {
	result := plus(2, 3, 4, 5, 6, 7)
	fmt.Println(result)
}
package main

import (
	"fmt"
)



func main() {
	name := "gunwoo ! ! ! ! ! ! Is my name"
	for index, letter := range name{
		fmt.Println(index, letter)
	}
	for _, letter := range name{
		fmt.Println(letter)
	}
	for _, letter := range name{
		fmt.Println(string(letter))
	}
}

slice and array

package main

import (
	"fmt"
)



func main() {
	foods := [3]string{"potato", "pizza", "hambuger"}
	for _, food := range foods{
		fmt.Println(food)
	}
	for i := 0; i < len(foods); i++{
		fmt.Println(foods[i])
	}
}

array를 만들기 전에 element의 갯수를 미리 정해줘야한다.

하지만 slice는 정해놓지 않고 무한대로 커질수 있다. [3] => [] 로 바꿔주면 끝

package main

import (
	"fmt"
)



func main() {
	foods := []string{"potato", "pizza", "hambuger"}
	fmt.Printf("%v\n", foods)
	foods = append(foods, "tomato")
	fmt.Printf("%v\n", foods)
	//append는 slice 추가 array에는 사용 불가
	fmt.Println(len(foods))
}

memory address

package main

import (
	"fmt"
)

func main() {
	a := 2
	b := a
	fmt.Println(&b, &a)
	//memory address 저장 => &
}

a, b는 다른곳에 저장

package main

import (
	"fmt"
)

func main() {
	a := 2
	b := &a
	fmt.Println(b, &a)
	//memory address 저장 => &

}

같은 위치에 저장 된다. 

 

package main

import (
	"fmt"
)

func main() {
	a := 2
	b := &a
	a = 50
	fmt.Println(*b)
	//memory address에 저장된 value 값을 보고 싶다
}


=>50

structs

package main

import "fmt"

type person struct {
	name string
	age int
}
func (p person) sayHello() {
	fmt.Printf("hello my name is %s and I'm %d years old", p.name, p.age)
}
func main() {
	gunwoo := person{name: "gunwoo", age: 31}
	gunwoo.sayHello()
}

p => person struct를 부른다. => p.name p.age , => p person 말고 p 자리에 아무 글자나 넣어도 된다

 

pointer

person.go

package person

import "fmt"

type Person struct {
	name string
	age int
}

func (p *Person) SetDetails (name string, age int) {
	p.name = name
	p.age = age
	fmt.Println("SetDetail' gunwoo:", p)
}

main.go

package main

import (
	"fmt"
	"goBlock/person"
)

	func main() {
		gunwoo := person.Person{}
		gunwoo.SetDetails("gunwoo", 12)
		fmt.Println("Main gunwoo", gunwoo)
	}

main.go에서 person 함수를 참조해 복사하는 것이 아니라 수정을 한다

 

 

'언어 > Go' 카테고리의 다른 글

genesis Block 생성  (0) 2022.07.21
If with a Twist  (0) 2022.02.13
for, range, ...args  (0) 2022.02.13
Functions part Two  (0) 2022.02.13
Functions part One  (0) 2022.02.13

댓글