-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelper.go
39 lines (36 loc) · 846 Bytes
/
helper.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package tftags
import (
"fmt"
"log"
"reflect"
"strconv"
)
// convert to string
func toString(v interface{}) string {
return fmt.Sprint(v)
}
// compare src and dest, if both kind are same, assign dest=src
// else try to convert src to dest type and set
func compareAndSet(dest reflect.Value, src interface{}) {
srcRef := reflect.ValueOf(src)
if srcRef.Kind() != dest.Kind() {
switch dest.Kind() {
case reflect.Int:
strSrc := toString(src)
if strSrc == "" {
return
}
intVal, err := strconv.Atoi(strSrc)
if err != nil {
log.Panicf("failed to convert %T to int", src)
}
dest.Set(reflect.ValueOf(intVal))
case reflect.String:
dest.Set(reflect.ValueOf(toString(src)))
default:
log.Panicf("cannot convert %s to %s", srcRef.Kind().String(), dest.Kind().String())
}
} else {
dest.Set(srcRef)
}
}