'Print value from Golang custom strcu
I am new to Golang. I have below code, Can someone please help to Print Only ID from the custom created struct?
type Currency struct {
ID uint `db:"id" json:"id"`
Name string `db:"name" json:"name"`
Code string `db:"code" json:"code"`
CreatedAt sql.NullTime `db:"createdAt" json:"createdAt"`
UpdatedAt sql.NullTime `db:"updatedAt" json:"updatedAt"`
}
type temp struct {
Currency map[string]Currency
}
func GetCurrencies(db *sqlx.DB) ([]Currency, error) {
sqlStatement := `SELECT * FROM "Currencies"`
var currencyRows []Currency
err := db.Select(¤cyRows, sqlStatement)
return currencyRows, err
}
func PrintC(db *sqlx.DB) {
Currencies, _ := GetCurrencies(db)
stores := []temp{}
for _, currency := range Currencies {
store := temp{
Currency: map[string]Currency{
currency.Name: {
ID: currency.ID,
Name: currency.Name,
Code: currency.Code,
CreatedAt: currency.CreatedAt,
UpdatedAt: currency.UpdatedAt,
},
},
}
stores = append(stores, store)
}
fmt.Println(stores)
}
Current Output:
[{map[Ethereum:{2 Ethereum ETH {2022-02-03 14:10:58.264 +0000 UTC true} {2022-02-03 14:10:58.264 +0000 UTC true}}]} {map[Bitcoin:{1 Bitcoin BTC {2022-02-03 14:10:59.471 +0000 UTC true} {2022-02-03 14:10:59.471 +0000 UTC true}}]}]
Expected Output:
// PRINT ONLY ETHEREUM ID // PRINT ONLY BITCOIN ID
Solution 1:[1]
You can implement Stringer interface and define the way how would you like to print out your struct. https://go.dev/tour/methods/17
Solution 2:[2]
This snippet bellow implements the Stringer interface which is required by the fmt package. Basically the fmt package look for this interface to print values.
func (cr Currency) String() string {
return fmt.Sprintf("%v", cr.ID)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | George |
| Solution 2 | mo_boustta |
