skip to Main Content

I need map the struct to create a JSON structure. The collector_id attribute in JSON should be able to take null value or int value.
I hace the follow code:

type purchaseInfo struct {
    CollectorID *int64 `json:"collector_id"`
}

func mapPurchaseInfo(collectorID int64) purchaseInfo {
    var collectorIDToSend *int64
    if collectorID < 0 {
        collectorIDToSend = nil
    } else {
        collectorIDToSend = collectorID
    }

    return purchaseInfo{
        CollectorID: collectorIDToSend,
    }
}

This code doesn’t compile, the collectorID can’t be assigned to collectorIDToSend.
Is there a way to be able to do this?

Thanks!

2

Answers


    • In the declaration of the mapPurchaseInfo function, to correctly assign the value passed in parameter to collectorIDToSend, the & operator must be used to retrieve the memory address of collectorID.
    • When constructing the purchaseInfo return variable, it is possible to put the fields of the structure directly as in the example.
    type purchaseInfo struct {
            CollectorID *int64 `json:"collector_id"`
        }
    
        func mapPurchaseInfo(collectorID int64) purchaseInfo {
            var collectorIDToSend *int64
            if collectorID < 0 {
                collectorIDToSend = nil
            } else {
                collectorIDToSend = &collectorID
            }
    
            return purchaseInfo{
                CollectorID: collectorIDToSend,
            }
        }
    
    Login or Signup to reply.
  1. type purchaseInfo struct {
        CollectorID *int64 `json:"collector_id"`
    }
    
    func mapPurchaseInfo(collectorID *int64) purchaseInfo {
        if *collectorID < 0 {
            return purchaseInfo{CollectorID: nil}
        }
        return purchaseInfo{
            CollectorID: collectorID,
        }
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search