|
1547 | 1547 |
|
1548 | 1548 | **[ Back to Top ⬆ ](#table-of-contents---golang)**
|
1549 | 1549 |
|
| 1550 | + 21. ### How would you determine the type of a variable and Which package to use for it? |
| 1551 | + |
| 1552 | + There are three different ways to find type of variable in Golang<br/> |
| 1553 | + * **reflect.TypeOf Function**: Using the golang inbuilt package reflect we can find the Type of variable |
| 1554 | + |
| 1555 | + ```go |
| 1556 | + package main |
| 1557 | + |
| 1558 | + |
| 1559 | + import ( |
| 1560 | + "fmt" |
| 1561 | + "reflect" |
| 1562 | + ) |
| 1563 | + |
| 1564 | + func main(){ |
| 1565 | + var string_type = "Hello Go"; |
| 1566 | + var complex_type = complex(9, 15); |
| 1567 | + |
| 1568 | + fmt.Println("string_type", reflect.TypeOf(string_type)) |
| 1569 | + fmt.Println("complex_type = ", reflect.TypeOf(complex_type)) |
| 1570 | + } |
| 1571 | + ``` |
| 1572 | + * **reflect.ValueOf.Kind() Function** : Using the golang inbuilt package reflect we can find the Type of variable |
| 1573 | + |
| 1574 | + ```go |
| 1575 | + package main |
| 1576 | + |
| 1577 | + |
| 1578 | + import ( |
| 1579 | + "fmt" |
| 1580 | + "reflect" |
| 1581 | + ) |
| 1582 | + |
| 1583 | + func main(){ |
| 1584 | + var string_type = "Hello Go"; |
| 1585 | + var complex_type = complex(9, 15); |
| 1586 | + |
| 1587 | + fmt.Println("string_type", reflect.ValueOf(string_type).Kind()) |
| 1588 | + fmt.Println("complex_type = ", reflect.TypeOf(complex_type).Kind()) |
| 1589 | + } |
| 1590 | + ``` |
| 1591 | + * **%T with Printf** : You can use Printf also to find value of variable |
| 1592 | + |
| 1593 | + ```go |
| 1594 | + package main |
| 1595 | + |
| 1596 | + |
| 1597 | + import ( |
| 1598 | + "fmt" |
| 1599 | + "reflect" |
| 1600 | + ) |
| 1601 | + |
| 1602 | + func main(){ |
| 1603 | + var string_type = "Hello Go"; |
| 1604 | + var complex_type = complex(9, 15); |
| 1605 | + |
| 1606 | + fmt.Printf("string_type=%T\n", string_type) |
| 1607 | + fmt.Printf("complex_type =%T\n", complex_type) |
| 1608 | + } |
| 1609 | + ``` |
| 1610 | + |
| 1611 | + **[ Back to Top ⬆ ](#table-of-contents---golang)** |
| 1612 | + |
| 1613 | + |
| 1614 | + |
| 1615 | + |
| 1616 | + |
1550 | 1617 |
|
1551 | 1618 | ### Table of Contents - Database Engineering
|
1552 | 1619 |
|
|
0 commit comments