Showing posts with label golang_type_conversion. Show all posts
Showing posts with label golang_type_conversion. Show all posts

Mar 19, 2021

[Go] untype type

Reference:
https://groups.google.com/g/golang-nuts/c/9EVmGFVoawg/m/nYXYaUcpCgAJ


Untyped bool, int, etc are the types of untyped constants:
https://golang.org/ref/spec#Constants

package main

const i = 42      // i is untyped int
const j = int(42) // j is int

var f float64 = i // ok because i is untyped int
var g float64 = j // compile error, type mismatch

func main() {
}

Mar 8, 2019

[Go] conversion rule

Conversion rules:

Since Golang 1.7
A non-constant value x can be converted to type T in any of these cases:
  • same sequence of fields (order matters due to memory layout, in C/C++/assembly/Golang, which includes padding.
    In C++, padding matters also due to object slicing (hey, we have inheritance in C++).
    Please refer to note:
    http://vsdmars.blogspot.com/2018/09/golangc-padding.html)
  • corresponding fields with same type.
  • x is assignable to T.
  • x's type and T have identical underlying types.
  • x's type and T are unnamed pointer types and their pointer base types have identical underlying types.
  • ignoring struct tags, x's type and T have identical underlying types.
  • ignoring struct tags, x's type and T are unnamed pointer types and their pointer base types have identical underlying types.

type Person struct {
    Name     string
    AgeYears int
    SSN      int
}

var aux struct {
    Name     string `json:"full_name"`
    AgeYears int    `json:"age"`
    SSN      int    `json:"social_security"`
}

var yeah Person = Person(aux)

Jun 22, 2018

[Go] type conversion

Unlike C++ strong type language it's hard to convert from different type name even they have the same memory layout, we can convert; however, through ptr. golang spec: https://golang.org/ref/spec#Assignability
package main

import (
 "fmt"
)

type type1 []struct {
    Field1 string
    Field2 int
}
type type2 []struct {
    Field1 string
    Field3 int // conversion must have same name. Why? Due to accessing the datamember name should be consistent.
}

func main() {
 t1 := type1{{"A", 1}, {"B", 2}}
 t2 := type2(t1)
 fmt.Println(t2)
}