Programming(74)
-
Go test: table driven test with Parallel()
우리는 test driven test를 위해 Unit test 코드를 작성합니다. 이 때 하나의 unit test function을 여러가지 다양한 방식으로 test 하기 위해 여러 parameter들을 table로 만들어 사용합니다. 다음은 그 예입니다. func TestA(t *testing.T) { t.Parallel() testCases := []struct { name string value int }{ { name: "case 1", value: 1, }, { name: "case 2", value: 2, }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { // test code here t.Log(tc.value) ..
2023.06.22 -
Go gotcha examples
예를들어 다음과 같은 대표적인 'Go gotcha'들이 존재합니다. variable shadowing Go 에서는 inner scope에서 같은 이름으로 변수를 선언할 수 있습니다. 이는 이전의 변수에 접근할 수 없게 만드는 소위 'shadowing' 역할을 수행합니다. func main() { a := 1 fmt.Println(a) if true { a := 2 fmt.Println(a) } fmt.Println(a) } 위 코드의 출력은 다음과 같습니다. 1 2 1 slices and arrays Go에서 slice와 array는 매우 유사한 type 입니다. slices는 arrays에 대한 references이며 동적인 길이를 갖습니다. 반면에 arrays는 고정된 길..
2023.06.22 -
Go에서 time의 ticker 사용
주기적으로 설정한 time tick 마다 깨어나서 동작하는 코드 peroid := 200 * time.Millisecond stop := make(chan struct{}, 1) go func() { ticker := time.NewTicker(period) defer ticker.Stop() for { select { case
2023.06.21 -
Go에서 CPU 사용량 측정
host machine의 CPU usage를 측정 import "github.com/shirou/gopsutil/cpu" period := 100 * time.Millisecond cpuInfo, err := cpu.Percent(period, false) if err != nil { return } c.usage = cpuInfo[0]container의 CPU usage를 측정 dat, err := ioutil.ReadFile(path) ... used, err := strconv.Atoi(strings.Replace(string(dat), "\n", "", 1)) ... time.Sleep(period) // process가 사용한 system time을 획득 var r syscall.Rusage s..
2023.06.21 -
Go 언어에서 reflect로 필드명과 값 획득 방법
func getKeyValueFromConfig(reflectValue reflect.Value, options *scenario.RequestOptions) { reflectType := reflectValue.Type() for i := 0; i < reflectValue.NumField(); i++ { field := reflectType.Field(i) value := reflectValue.Field(i).Interface() fmt.Printf("Field: %s, Value: %v\n", field.Name, value) options.InputOptions[field.Name] = value } }
2023.06.20 -
고 언어 (Go lang)에서 값의 스왑 (swap) 방법
Go lang에서 값을 swap 하는 방법에 대해 살펴보겠습니다. 간단하게 다음의 문제를 풀면서 swap을 적용해 보겠습니다. nums = [3, 2, 1, 4] 위와같은 배열이 있습니다. 배열의 값 1은 배열의 좌측끝으로, 배열 내 값 4는 배열의 우측 끝으로 이동시키고자 합니다. 이때 이동 방법은 인접한 두 개의 값을 서로 swap 하는 방법으로만 이동 할 수 있습니다. 다음과 같이 위 알고리즘 문제를 해결하면서 swap을 적용해 볼 수 있습니다. func swap(val1 *int, val2 *int) { temp := *val1 *val1 = *val2 *val2 = temp } func semiOrderedPermutation(nums []int) int { i := 0 one_idx := -1..
2023.06.05