Y
Y
Yuri Velmesov2019-02-14 16:50:34
go
Yuri Velmesov, 2019-02-14 16:50:34

Golang, How to merge two structs into one new one with all the fields from the previous two?

We have a bottleneck on the backend when generating a price list using php, about 30 seconds, tested on Go, 1-2 seconds.
There is an example in php:

// Запрос к базе к таблице товаров
// $sql1 .....

// Здесь у нас массив товаров в итоге
$products = [];

// Здесь ключи массива формируются сами от 0 и дальше...
while ($row = mysqli_fetch_assoc($sql1)) {
    $products[]['Name']    = $row['Name'];
    $products[]['Code']    = $row['Code'];
    $products[]['InStock'] = $row['InStock'];
}

// Запрос к базе к таблице товаров
// $sql2 .....

// Здесь у нас массив цен товаров в итоге
$prices = [];

// Здесь ключами массива ставим код товара
// Чтобы в дальнейшем можно было обращаться к ценам
// к примеру так: $prices[$product['code']]['price1']
while ($row = mysqli_fetch_assoc($sql2)) {
    $prices[$row['code']]['Price1'] = $row['Price1'];
    $prices[$row['code']]['Price2'] = $row['Price2'];
}

// Теперь создаем итоговый общий массив со всеми данными
$productFullData = [];

foreach($products as $product) {
    $productFullData[]['Name']    = $product['Name'];
    $productFullData[]['Code']    = $product['Code'];
    $productFullData[]['InStock'] = $product['InStock'];
    $productFullData[]['Price1']  = $prices[$product['Code']]['Price1'];
    $productFullData[]['Price2']  = $prices[$product['Code']]['Price2'];
}

// И дальше уже оперируем с массивом $productFullData...
// Формируем прайс .xlsx

And there is an example in Go:
package main

// Products список товаров (название, цена, остаток на складе)
type Products struct {
  Name    string
  Code    int
  InStock int
}

// Prices список цен и код
type Prices struct {
  Price2 int
  Price3 int
  Code   int
}

// ProductFullData итоговые данные
type ProductFullData struct {
  Name    string
  Code    int
  InStock int
  Price2  int
  Price3  int
}

func main() {
  // Получили товары
  products := model.Products()

  // Получили цены
  prices := model.Prices()

  // Вопрос!!!
  // Как их обединить в один чтобы все
  // данные были в одной структуре ProductFullData

  // И дальше уже оперируем с массивом $productFullData...
  // Формируем прайс .xlsx
}

I deliberately skipped sections of the code with queries to the database, everything is clear with this.
I have a misunderstanding exactly with how to make one new structure out of two structures with all the data, but attention that when generating the second structure, the keys for the prices were product codes, and not by order (0,1,2...)
In the code examples, I commented out everything to make it clear.
I’ll clarify right away so that they don’t kick me with the crowd :) I came to Go a week ago and I already understand its power, but not everything lends itself right away.
I will accept both code examples and references to the docs.
But not like this, follow the links here and smoke the manuals, at least so that you can teach in this direction or try this ...
Thank you all in advance!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Pavlyuk, 2019-02-14
@yury-gubsky

Simply create a structure by filling in its fields.

fullData := ProductFullData{
  Name: product.Name,
  Code: price.Code,
  InStock: product.InStock,
  Price2: price.Price2,
  Price3: price.Price2,
}

M
Maksim B, 2019-02-15
@Sundagy

you can write links in gorm models and take an array of ready-made structures productfulldara in one line immediately from the database

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question