Jak znaleźć typ obiektu w Go?

Jak znaleźć typ obiektu w Go? W Pythonie po prostu używam typeof do pobierania typu obiektu. Podobnie W Go, czy istnieje sposób, aby wdrożyć to samo ?

Oto kontener, z którego iteruję:

for e := dlist.Front(); e != nil; e = e.Next() {
    lines := e.Value
    fmt.Printf(reflect.TypeOf(lines))
}

Nie jestem w stanie uzyskać typu linii obiektu, który jest tablicą łańcuchów.

 428
Author: golopot, 2013-11-24

14 answers

Pakiet go reflection zawiera metody kontroli typu zmiennych.

Poniższy fragment wyświetli Typ odbicia string, integer I float.

package main

import (
    "fmt"
    "reflect"
)

func main() {

    tst := "string"
    tst2 := 10
    tst3 := 1.2

    fmt.Println(reflect.TypeOf(tst))
    fmt.Println(reflect.TypeOf(tst2))
    fmt.Println(reflect.TypeOf(tst3))

}

Wyjście:

Hello, playground
string
int
float64

Zobacz: http://play.golang.org/p/XQMcUVsOja aby zobaczyć go w akcji.

Więcej dokumentacji tutaj: http://golang.org/pkg/reflect/#Type

 516
Author: dethtron5000,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-04-04 07:43:32

Znalazłem 3 sposoby zwracania typu zmiennej w czasie wykonywania:

Using string formatowanie

func typeof(v interface{}) string {
    return fmt.Sprintf("%T", v)
}

Korzystanie z pakietu reflect

func typeof(v interface{}) string {
    return reflect.TypeOf(v).String()
}

Używanie twierdzeń typu

func typeof(v interface{}) string {
    switch v.(type) {
    case int:
        return "int"
    case float64:
        return "float64"
    //... etc
    default:
        return "unknown"
    }
}

Każda metoda ma inny najlepszy przypadek użycia:

  • Formatowanie łańcuchów-krótkie i niewielkie rozmiary (nie jest konieczne importowanie pakietu reflect)

  • Reflect pakiet - gdy potrzeba więcej szczegółów na temat rodzaju mamy dostęp do pełnych możliwości odbicia

  • Asercje typu-umożliwia grupowanie typów, na przykład rozpoznaje wszystkie typy int32, int64, UInt32, UInt64 jako "int"

 496
Author: Grzegorz Luczywo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-04-05 11:23:04

Użyj reflect pakiet:

Package reflect implementuje run-time reflection, pozwalając programowi na manipuluj obiektami o dowolnych typach. Typowym zastosowaniem jest wartość z interfejsem typu statycznego {} i wyodrębnić jego typ dynamiczny informacje poprzez wywołanie TypeOf, które zwraca typ.

package main

import (
    "fmt"
    "reflect"
)

func main() {
    b := true
    s := ""
    n := 1
    f := 1.0
    a := []string{"foo", "bar", "baz"}

    fmt.Println(reflect.TypeOf(b))
    fmt.Println(reflect.TypeOf(s))
    fmt.Println(reflect.TypeOf(n))
    fmt.Println(reflect.TypeOf(f))
    fmt.Println(reflect.TypeOf(a))
}

Produkuje:

bool
string
int
float64
[]string

Plac zabaw

Przykład użycia ValueOf(i interface{}).Kind():

package main

import (
    "fmt"
    "reflect"
)

func main() {
    b := true
    s := ""
    n := 1
    f := 1.0
    a := []string{"foo", "bar", "baz"}

    fmt.Println(reflect.ValueOf(b).Kind())
    fmt.Println(reflect.ValueOf(s).Kind())
    fmt.Println(reflect.ValueOf(n).Kind())
    fmt.Println(reflect.ValueOf(f).Kind())
    fmt.Println(reflect.ValueOf(a).Index(0).Kind()) // For slices and strings
}

Produkuje:

bool
string
int
float64
string

Plac zabaw

 53
Author: Intermernet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-11-29 10:30:30

Aby uzyskać reprezentację ciągu znaków:

Z http://golang.org/pkg/fmt/

%t a Go-reprezentacja składni typu wartości

package main
import "fmt"
func main(){
    types := []interface{} {"a",6,6.0,true}
    for _,v := range types{
        fmt.Printf("%T\n",v)
    }
}

Wyjścia:

string
int
float64
bool
 45
Author: globby,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-07 21:41:09

Trzymałbym się z dala od refleksji. paczka. Zamiast tego użyj %T

package main

import (
    "fmt"
)

func main() {
    b := true
    s := ""
    n := 1
    f := 1.0
    a := []string{"foo", "bar", "baz"}

    fmt.Printf("%T\n", b)
    fmt.Printf("%T\n", s)
    fmt.Printf("%T\n", n)
    fmt.Printf("%T\n", f)
    fmt.Printf("%T\n", a)
 }
 16
Author: harold ramos,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-01 19:34:14

Najlepszym sposobem jest użycie koncepcji odbicia w Google.
reflect.TypeOf podaje Typ wraz z nazwą pakietu
reflect.TypeOf().Kind() daje Typ podkreślenia

 13
Author: Jiten,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-02 18:36:28

Aby być krótkim, należy użyć fmt.Printf("%T", var1) lub jego innych wariantów w pakiecie fmt.

 10
Author: pr-pal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-12-04 03:41:06

Możesz sprawdzić typ dowolnej zmiennej / instancji w czasie wykonywania za pomocą funkcji "reflect" pakiety TypeOf lub za pomocą fmt.Printf():

package main

import (
   "fmt"
   "reflect"
)

func main() {
    value1 := "Have a Good Day"
    value2 := 50
    value3 := 50.78

    fmt.Println(reflect.TypeOf(value1 ))
    fmt.Println(reflect.TypeOf(value2))
    fmt.Println(reflect.TypeOf(value3))
    fmt.Printf("%T",value1)
    fmt.Printf("%T",value2)
    fmt.Printf("%T",value3)
}
 4
Author: Kabeer Shaikh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-23 03:03:34

Aby uzyskać Typ pól w strukturze

package main

import (
  "fmt"
  "reflect"
)

type testObject struct {
  Name   string
  Age    int
  Height float64
}

func main() {
   tstObj := testObject{Name: "yog prakash", Age: 24, Height: 5.6}
   val := reflect.ValueOf(&tstObj).Elem()
   typeOfTstObj := val.Type()
   for i := 0; i < val.NumField(); i++ {
       fieldType := val.Field(i)
       fmt.Printf("object field %d key=%s value=%v type=%s \n",
          i, typeOfTstObj.Field(i).Name, fieldType.Interface(),
          fieldType.Type())
   }
}

Wyjście

object field 0 key=Name value=yog prakash type=string 
object field 1 key=Age value=24 type=int 
object field 2 key=Height value=5.6 type=float64

Zobacz w IDE https://play.golang.org/p/bwIpYnBQiE

 4
Author: negi Yogi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-08-20 07:31:57

Jeśli mamy tę zmienną:

var counter int = 5
var message string  = "Hello"
var factor float32 = 4.2
var enabled bool = false

1: fmt.Printf %t format: aby skorzystać z tej funkcji należy zaimportować " fmt "

fmt.Printf("%T \n",factor )   // factor type: float32

2: zastanów się.TypeOf function: aby skorzystać z tej funkcji należy zaimportować "reflect"

fmt.Println(reflect.TypeOf(enabled)) // enabled type:  bool

3: zastanów się.ValueOf (X).Kind () : Aby skorzystać z tej funkcji należy zaimportować "reflect"

fmt.Println(reflect.ValueOf(counter).Kind()) // counter type:  int
 2
Author: Hamed Naeemaei,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-04-15 19:51:15

Możesz użyć reflect.TypeOf.

  • Typ podstawowy(np.: int, string): zwróci swoją nazwę (np.: int, string)
  • struct: zwróci coś w formacie <package name>.<struct name> (np.: main.test)
 0
Author: 夜阑听风,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-11 06:07:39

Możesz użyć: interface{}..(type) Jak w tym

package main
import "fmt"
func main(){
    types := []interface{} {"a",6,6.0,true}
    for _,v := range types{
        fmt.Printf("%T\n",v)
        switch v.(type) {
        case int:
           fmt.Printf("Twice %v is %v\n", v, v.(int) * 2)
        case string:
           fmt.Printf("%q is %v bytes long\n", v, len(v.(string)))
       default:
          fmt.Printf("I don't know about type %T!\n", v)
      }
    }
}
 0
Author: Hasan A Yousef,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-06-01 07:30:31

Reflect Pakiet przychodzi na ratunek:

reflect.TypeOf(obj).String()

Sprawdź to demo

 -2
Author: Ismayil Niftaliyev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-04 12:18:21

Możesz po prostu użyć pakietu fmt FMT.Metoda Printf (), więcej informacji: https://golang.org/pkg/fmt/

Przykład: https://play.golang.org/p/aJG5MOxjBJD

 -2
Author: JORDANO,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-07 20:39:55