Print value from Golang custom strcu

Viewed 53

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(&currencyRows, 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

2 Answers

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)
}
Related