#what is the point here ?

10 messages · Page 1 of 1 (latest)

stoic anvil
#
package main 

import "fmt"

type str string 

func check[T ~string](x T) T {
    return x
}

func main() {
    var mytype string = "hello world"

    fmt.Println(check(mytype))
}

1 - i don't understand the point of ~ it just restrict arguments types to a certain type which doesn't make any sense for me

2 - what increases the confusion is that both str and string works which makes sense but confusing

feral urchin
#

~T means the types that have same basic type.
In your case, you can use + oper for any type that have the basic type string, and you can safely cast anything into string or anything else that basic type is string (such as str in your code) if it's basic type is string.

#

However, if you used ~, you cannot invoke the methods the T has, you can only use the operation that string support

feral urchin
#

"a" + "b" == "ab"

stoic anvil
#

i don't understand what you mean by basic type

feral urchin
#

string, int8/16/32/64, float32/64, complex64/128 etc. are the basic types

#

but things like type str string, str is not a basic type, it's a user defined type which have basic type string

#

user defined type can have methods, but basic type haven't

#

and the usage for ~T is when you only care about the basic type, but don't really care the actually type, you may understand it as a kind of interface.
For example:

type HexInt int
func (n HexInt)String()(string){
  return fmt.Sprintf("%x", (int)(n))
}

func abs[T ~int](x T)(T){
  if x < 0 {
    return -x
  }
  return x
}

func main(){
  fmt.Println(abs((int)(-123)))
  fmt.Println(abs((HexInt)(-123)))
}

In the function abs, you don't care what method does HexInt have, you only care about if the T can compare with a integer, and it can be negate. Then the function abs will work.