我有一个请求两组数据的函数。我想在两组数据中找到匹配项,并使用主数据集中的数据更新我们的数据库。
问题在于数据是接口(interface)类型。我的想法是遍历它们并找到一个匹配项,但我不确定是否有更好的主意。
如何在 Go 中迭代接口(interface)并在 BackfillMissingData 函数中匹配这些数据点?
这就是我目前所拥有的。
type Account struct {
SalesForceAccountId string
}
func FindIncompleteAccounts(qExec *database.PostgresDB) interface{} {
var salesForceAccountId string
rows, err := qExec.Query(
`query string`)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
var accounts []Account
for rows.Next() {
err := rows.Scan(&salesForceAccountId)
if err != nil {
log.Fatal(err)
}
accounts = append(accounts, Account{SalesForceAccountId: salesForceAccountId})
}
err = rows.Err()
if err != nil {
log.Fatal(err)
}
return accounts
}
var client = &http.Client{Timeout: 10 * time.Second}
type Payload struct {
Companies []Companies `json:"companies"`
}
type Companies struct {
CompanyId int `json:"companyId"`
Properties struct {
SalesForceAccountId struct {
Value string `json:"value"`
}
}
}
func RequestCompanies() interface{} {
url := fmt.Sprintf("external api", apiKey)
client := http.Client{
Timeout: time.Second * 2,
}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Fatal(err)
}
req.Header.Set("User-Agent", "fetching-companies")
res, getErr := client.Do(req)
if getErr != nil {
log.Fatal(getErr)
}
body, readErr := ioutil.ReadAll(res.Body)
if readErr != nil {
log.Fatal(readErr)
}
companies := Payload{}
jsonErr := json.Unmarshal([]byte(body), &companies)
if jsonErr != nil {
log.Fatal(err)
}
return companies
}
func BackfillMissingData(qExec *database.PostgresDB) error {
companies := RequestCompanies()
incompleteAccounts := FindIncompleteAccounts(qExec)
}
主数据集
{[{837002081 {{0012a00000IO7ToAAL}}} {837404922 {{001U000000i0xngIAA}}} {840907652 {{0012a00000Icl6gAAB}}}]}
本地数据集
[{0010B00001qY5GoRAS}]
主数据集中的第一个数字是公司 ID,我想用我的本地数据检查主数据集中的第二个项目。
最佳答案
问题是 RequestCompanies()
和 FindIncompleteAccounts(...)
函数返回“空接口(interface)”接口(interface){}
,这意味着您实际上无法按原样使用这些值做任何事情。
这些方法不应返回空接口(interface),而应返回它们实际表示的结构类型(例如 []Account
和 Payload
)或抽象操作的接口(interface)那些与您的任务相关的数据。
这样您就可以比较两个数据集中元素之间的属性(例如假设的 Account.ID
和 Payload.Result.AccountID
)并执行您的集合交集和最终更新。
关于go - 找到两组数据之间的匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53103742/