尝试将结构映射到我公开的API结构

时间:2018-04-25 17:56:41

标签: go

我正在编写映射函数,将我的内部模型映射到我将在API中公开的模型。

如何映射Locations属性。我是否适合他们?我是否必须先启动UserApi位置?

我对如何最好地做到这一点感到困惑,没有任何例外情况等。

func mapUserToApi(user User) UserApi {
  api := &UserApi{
     Id: user.Id,
     ..
     ..
  }

  for index, location := range user.Locations {
    /// ????????????
  }

  return api
}

func mapLocationToApi(location Locatio) LocationApi {
  ..
}


type User struct {
  Id int

  Locations []Location
}

type UserApi struct {
  Id int

  Locations []LocationApi
}

2 个答案:

答案 0 :(得分:1)

首先分配然后循环范围

func mapUserToApi(user User) UserApi {
  api := &UserApi{
     Id: user.Id,
     Locations: make([]LocationApi, len(user.Locations), len(user.Locations)),
  }

  for index, location := range user.Locations {
    api.Locations[index] = mapLocationToApi(location)
  }

  return api
}

答案 1 :(得分:0)

range可以正常运行您想要做的事情。下面的代码是非特定的,可以推广到您的用例。

func mapLocationsToModifiedLocations(user User) []ModifiedLocation {
    // initialize a new slice with the type of your API-appropriate output
    // and a length of zero
    var output := make([]ModifiedLocation, 0)

    // iterate over your input data
    for _, element := range user.Locations {
        // use append to automatically re-size the output array as needed
        output = append(output, modifyLocation(location))
    }

    return output
}