Andrey
Фак
Andrey
Не, все равно
Andrey
а теперь ты скорее всего тег не указал
Andrey
после работы с джунами приходится преобретать экстрасенсорные способности, по другому не выжить )
Alexander
вообще, хороший тон не: User_id string а UserID string `json:"user_id"`
Andrey
А про какой тэг идет речь?
Andrey
json:"user_id" вот это называется тег
Andrey
выше пример
Andrey
так элемент дерева так и называется Positions только с маленькой буквы
Илья
https://mholt.github.io/json-to-go/
Илья
так элемент дерева так и называется Positions только с маленькой буквы
значит имя поля должно быть с большой буквы, а тег "positions"
Andrey
Ну так сейчас так и есть
Andrey
Ну так сейчас так и есть
на скрине не так
Andrey
Andrey
Ну я исправил же
Andrey
и не работает?
Andrey
Пустой массив
Andrey
Type читает
Илья
скинь json
Andrey
у тебя там в боди дата лежала
Andrey
может ты ее забыл?
Andrey
там не было data это golang рисовал ее
Andrey
тогда нужен json
Andrey
без него не понять что не так
Alexander
Пустой массив
https://mholt.github.io/json-to-go/ - вставляешь сюда, то что приходит, и смотришь, что получилось. я же уже предлагал
Илья
на одном месте стоите)
Andrey
да я уже переживаю за его json больше чем за свои отношения
Andrey
:D
Andrey
{ "type": "SELL", "id": "e7913bd9-df28-4329-ad70-a9f88caf29f7", "extras": {}, "number": 31876, "close_date": "2022-08-22T16:10:01.000+0000", "time_zone_offset": 10800000, "session_id": "bed5ea1e-a221-4d5b-8201-94b0f203a623", "session_number": 483, "close_user_id": "20210112-D358-40CE-80E1-522BF8624A4D", "device_id": "20210430-81BC-4052-8084-DBE6ACA6356C", "store_id": "20201125-0822-40BB-80F9-C867E393EEB5", "user_id": "01-000000003606709", "body": { "positions": [ { "product_id": "48e62714-5743-11eb-bed8-d43d7e343981", "quantity": 0.462, "initial_quantity": 10.659, "quantity_in_package": null, "bar_code": null, "product_type": "NORMAL", "mark": null, "mark_data": null, "alcohol_by_volume": 0, "alcohol_product_kind_code": 0, "tare_volume": 0, "code": "01887", "product_name": "Хек тушка с/м", "measure_name": "кг", "id": 233987, "uuid": "5c59adcd-3f19-4e31-8c3a-ad2117f598c7", "extra_keys": [], "sub_positions": [], "measure_precision": 3, "price": 350, "cost_price": 0, "result_price": 350, "sum": 161.7, "tax": { "type": "NO_VAT", "sum": 0, "result_sum": 0 }, "result_sum": 161.7, "position_discount": null, "doc_distributed_discount": null, "print_group_id": "46dd89f0-3a54-470a-a166-ad01fa34b86a", "splitted_positions": null, "attributes_choices": null, "settlement_method": { "type": "CHECKOUT_FULL", "amount": null }, "agent_requisites": null } ], "doc_discounts": [], "payments": [ { "id": "1652ea81-b00b-497a-899f-6767c79ca67f", "parent_id": null, "sum": 161.7, "type": "CASH", "parts": [ { "print_group_id": "46dd89f0-3a54-470a-a166-ad01fa34b86a", "part_sum": 161.7, "change": 0 } ], "app_payment": null, "merchant_info": null, "bank_info": null, "app_info": { "app_id": null, "name": "Наличные" } } ], "print_groups": [ { "id": "46dd89f0-3a54-470a-a166-ad01fa34b86a", "type": "CASH_RECEIPT", "org_name": null, "org_inn": null, "org_address": null, "taxation_system": null, "medicine_attributes": null } ], "pos_print_results": [ { "receipt_number": 9780, "document_number": 52936, "session_number": 482, "receipt_date": "22082022", "receipt_time": "1901", "fn_reg_number": null, "fiscal_sign_doc_number": "3877747380", "fiscal_document_number": 30262, "fn_serial_number": "9287440301072378", "kkt_serial_number": "00307901765100", "kkt_reg_number": "0005416293036444", "print_group_id": "46dd89f0-3a54-470a-a166-ad01fa34b86a", "check_sum": 161.7 } ], "sum": 161.7, "result_sum": 161.7, "customer_email": null, "customer_phone": null }, "counterparties": null, "created_at": "2022-08-22T16:12:42.749+0000", "version": "V2" }
Alexander
на одном месте стоите)
да я уже не понимаю, как можно спрашивать вопрос, получать ответ и продолжать задавать тот же самый вопрос дальше
Andrey
Ладно ребят не стебитесь)
Andrey
ну валидатор говорит что у тебя на ProductID нет тега
Andrey
по JSON все норм должно быть, где-то ошибка
Andrey
type AutoGenerated struct { Type string `json:"type"` ID string `json:"id"` Extras struct { } `json:"extras"` Number int `json:"number"` CloseDate string `json:"close_date"` TimeZoneOffset int `json:"time_zone_offset"` SessionID string `json:"session_id"` SessionNumber int `json:"session_number"` CloseUserID string `json:"close_user_id"` DeviceID string `json:"device_id"` StoreID string `json:"store_id"` UserID string `json:"user_id"` Body struct { Positions []struct { ProductID string `json:"product_id"` Quantity float64 `json:"quantity"` InitialQuantity float64 `json:"initial_quantity"` QuantityInPackage interface{} `json:"quantity_in_package"` BarCode interface{} `json:"bar_code"` ProductType string `json:"product_type"` Mark interface{} `json:"mark"` MarkData interface{} `json:"mark_data"` AlcoholByVolume int `json:"alcohol_by_volume"` AlcoholProductKindCode int `json:"alcohol_product_kind_code"` TareVolume int `json:"tare_volume"` Code string `json:"code"` ProductName string `json:"product_name"` MeasureName string `json:"measure_name"` ID int `json:"id"` UUID string `json:"uuid"` ExtraKeys []interface{} `json:"extra_keys"` SubPositions []interface{} `json:"sub_positions"` MeasurePrecision int `json:"measure_precision"` Price int `json:"price"` CostPrice int `json:"cost_price"` ResultPrice int `json:"result_price"` Sum float64 `json:"sum"` Tax struct { Type string `json:"type"` Sum int `json:"sum"` ResultSum int `json:"result_sum"` } `json:"tax"` ResultSum float64 `json:"result_sum"` PositionDiscount interface{} `json:"position_discount"` DocDistributedDiscount interface{} `json:"doc_distributed_discount"` PrintGroupID string `json:"print_group_id"` SplittedPositions interface{} `json:"splitted_positions"` AttributesChoices interface{} `json:"attributes_choices"` SettlementMethod struct { Type string `json:"type"` Amount interface{} `json:"amount"` } `json:"settlement_method"` AgentRequisites interface{} `json:"agent_requisites"` } `json:"positions"` DocDiscounts []interface{} `json:"doc_discounts"` Payments []struct { ID string `json:"id"` ParentID interface{} `json:"parent_id"` Sum float64 `json:"sum"` Type string `json:"type"` Parts []struct { PrintGroupID string `json:"print_group_id"` PartSum float64 `json:"part_sum"` Change int `json:"change"` } `json:"parts"` AppPayment interface{} `json:"app_payment"` MerchantInfo interface{} `json:"merchant_info"` BankInfo interface{} `json:"bank_info"` AppInfo struct { AppID interface{} `json:"app_id"` Name string `json:"name"` } `json:"app_info"` } `json:"payments"` PrintGroups []struct { ID string `json:"id"` Type string `json:"type"` OrgName interface{} `json:"org_name"` OrgInn interface{} `json:"org_inn"` OrgAddress interface{} `json:"org_address"` TaxationSystem interface{} `json:"taxation_system"` MedicineAttributes interface{} `json:"medicine_attributes"` } `json:"print_groups"`
Andrey
PosPrintResults []struct { ReceiptNumber int `json:"receipt_number"` DocumentNumber int `json:"document_number"` SessionNumber int `json:"session_number"` ReceiptDate string `json:"receipt_date"` ReceiptTime string `json:"receipt_time"` FnRegNumber interface{} `json:"fn_reg_number"` FiscalSignDocNumber string `json:"fiscal_sign_doc_number"` FiscalDocumentNumber int `json:"fiscal_document_number"` FnSerialNumber string `json:"fn_serial_number"` KktSerialNumber string `json:"kkt_serial_number"` KktRegNumber string `json:"kkt_reg_number"` PrintGroupID string `json:"print_group_id"` CheckSum float64 `json:"check_sum"` } `json:"pos_print_results"` Sum float64 `json:"sum"` ResultSum float64 `json:"result_sum"` CustomerEmail interface{} `json:"customer_email"` CustomerPhone interface{} `json:"customer_phone"` } `json:"body"` Counterparties interface{} `json:"counterparties"` CreatedAt string `json:"created_at"` Version string `json:"version"` }
Andrey
не влазиет в одно сообщение
Илья
на go.dev/play закинь
Andrey
и мой совет. всегда используй теги, даже если поля называются так же как и поля в json, это идеологически правильно, потому что в данном контексте тег это представление данных а поля в структуре это хранение данных
Andrey
когда читаешь код и видишь json теги то понимаешь что в эту структуру где-то будет маршалиться json
Andrey
а если не видишь тегов, то можешь спокойно поменять называние поля и долго ловить багу почему оттуда отправили а к тебе не пришло
Andrey
так у меня структура таже самая
Andrey
А позишен без строчек получается
Andrey
Maria
ну это просто я формально из else перенесла. Спасибо, пытаюсь смотреть про бенчмарки. а вывод пока такой у меня (это, конечно, всем интересно): без else в if имеет смысл заключать маловероятный случай, требующий больших вычислений...
Ну вот, написала через testing (хотя в описании вроде сказано, что он всё равно к типу time.Duration обращается, ну ладно) положила тут: https://go.dev/play/p/_7sT0KAehY7 (расчеты формальные и бессмысленные) Benchmark1 - для if-else Benchmark2 - для выноса кода из else вперёд if (раз уж мы анализируем выгоду от такого переноса) Benchmark1povtory - как Benchmark1, но те блоки, которые внутри if и else, повторяются по 100 раз - чтобы имитировать сложный код Benchmark2povtory - как Benchmark2, но те блоки, которые внутри if и бывшего else (то есть теперь перед if), повторяются по 100 раз - чтобы имитировать сложный код В итоге то, что насчитывает тест для Benchmark1 и Benchmark2, не сильно отличается (около 3,5 ns/op) Для Benchmark1povtory время 20 ns/op для Benchmark2povtory - 30 ns/op Что и следовало ожидать, т.к. вынесенный вперед блок из else выполняется всегда, а внутри if - через раз, итого в полтора раза дольше, чем при использовании if-else. Надеюсь, удалось убедить компилятор честно отрабатывать все ветвления, я пока не умею это смотреть. В общем, или я ошиблась, или if-else - это лучше, чем предзадание+if. Прошу прощения, что занудно, зато мне так веселее разбираться...
Andrey
type AutoGenerated struct { Type string `json:"type"` ID string `json:"id"` Extras struct { } `json:"extras"` Number int `json:"number"` CloseDate string `json:"close_date"` TimeZoneOffset int `json:"time_zone_offset"` SessionID string `json:"session_id"` SessionNumber int `json:"session_number"` CloseUserID string `json:"close_user_id"` DeviceID string `json:"device_id"` StoreID string `json:"store_id"` UserID string `json:"user_id"` Body struct { Positions []struct { ProductID string `json:"product_id"` Quantity float64 `json:"quantity"` InitialQuantity float64 `json:"initial_quantity"` QuantityInPackage interface{} `json:"quantity_in_package"` BarCode interface{} `json:"bar_code"` ProductType string `json:"product_type"` Mark interface{} `json:"mark"` MarkData interface{} `json:"mark_data"` AlcoholByVolume int `json:"alcohol_by_volume"` AlcoholProductKindCode int `json:"alcohol_product_kind_code"` TareVolume int `json:"tare_volume"` Code string `json:"code"` ProductName string `json:"product_name"` MeasureName string `json:"measure_name"` ID int `json:"id"` UUID string `json:"uuid"` ExtraKeys []interface{} `json:"extra_keys"` SubPositions []interface{} `json:"sub_positions"` MeasurePrecision int `json:"measure_precision"` Price int `json:"price"` CostPrice int `json:"cost_price"` ResultPrice int `json:"result_price"` Sum float64 `json:"sum"` Tax struct { Type string `json:"type"` Sum int `json:"sum"` ResultSum int `json:"result_sum"` } `json:"tax"` ResultSum float64 `json:"result_sum"` PositionDiscount interface{} `json:"position_discount"` DocDistributedDiscount interface{} `json:"doc_distributed_discount"` PrintGroupID string `json:"print_group_id"` SplittedPositions interface{} `json:"splitted_positions"` AttributesChoices interface{} `json:"attributes_choices"` SettlementMethod struct { Type string `json:"type"` Amount interface{} `json:"amount"` } `json:"settlement_method"` AgentRequisites interface{} `json:"agent_requisites"` } `json:"positions"` DocDiscounts []interface{} `json:"doc_discounts"` Payments []struct { ID string `json:"id"` ParentID interface{} `json:"parent_id"` Sum float64 `json:"sum"` Type string `json:"type"` Parts []struct { PrintGroupID string `json:"print_group_id"` PartSum float64 `json:"part_sum"` Change int `json:"change"` } `json:"parts"` AppPayment interface{} `json:"app_payment"` MerchantInfo interface{} `json:"merchant_info"` BankInfo interface{} `json:"bank_info"` AppInfo struct { AppID interface{} `json:"app_id"` Name string `json:"name"` } `json:"app_info"` } `json:"payments"` PrintGroups []struct { ID string `json:"id"` Type string `json:"type"` OrgName interface{} `json:"org_name"` OrgInn interface{} `json:"org_inn"` OrgAddress interface{} `json:"org_address"` TaxationSystem interface{} `json:"taxation_system"` MedicineAttributes interface{} `json:"medicine_attributes"` } `json:"print_groups"`
Я таки и не понял в чем проблема, массив пустой
Andrey
https://go.dev/play/p/zR4AGNQ1Tf6
Andrey
https://go.dev/play/p/zR4AGNQ1Tf6
тебе го говорит в чем проблема
Andrey
https://go.dev/play/p/Yz8IukTwVWi
Andrey
https://go.dev/play/p/qZhHpMLjjju
Andrey
вот рабочий вариант а твоя ошибка это уже другой вопрос )
Andrey
Вот прикол
Andrey
Тоесть GO в случае ошибки структуру бросает наполовину заполненной?
Andrey
Прикол в том что верхние поля то заполнены структуры
Andrey
ну тут вопрос не к го а к маршалеру стандартному
Andrey
ну стандартная либа по мне часть языка)
Andrey
Все понятно, ни в каком языке такого не видел, вот почему и понять не мог, а ошибку я даже не мониторил
Null
⚠️ Время изучать Golang! 📌 24 августа в 20:00 мск пройдет открытый урок «Примитивы синхронизации в Go» в OTUS. На вебинаре с экспертом мы научимся пользоваться частью механизмов синхронизации и бороться с «гонками» в Go. ❓ Что вас ждет на занятии? ✅ Поговорим про группу ожидания (sync.WaitGroup); ✅ Затронем гарантировано одноразовое выполнение (sync.Once); ✅ Обсудим «простой» мьютекс (sync.Mutex) и детектор гонок (race detector). ➡️ Все остальные необходимые навыки для работы Go-разработчиком ждут вас на онлайн-курсе «Golang Developer. Professional». 👉 Перед встречей пройдите вступительный тест https://otus.pw/UwNC/
Вова
Добрый день. Пробую в VSCode отключить в workspace Go расширения для других языков. И столкнулся с трудностями касательно модулей. В качестве workspace выбираю папку, в которой лежат проекты, и в Explorer файлы подсвечиваются красным, из за того что не может найти плагины. Из вариантов которые мне попадались, это скачать portable vscode и настроить отдельно под каждый язык, но это громоздко... Может подскажите другие варианты?
Maks
Обычно воркспейс это папка текущего проекта.
Maks
А расширения для разных языков одновременно установлены и работают не мешая друг другу
Alexander
Я заплачу сейчас
Alexander
Одно и то же
Andrey
Вот блятть почемууу?
Ну рассказывай , где болит)
Alexander
От вас болит сердце
Юра (Юрий Александрович)
Какого типа боль? Жгучая, режущая, давящая?
Andrey
Все симптомы показываю что таки жопа а не сердце))
Andrey
Ну расскажи то хоть от чего бомбишь
Andrey
Ну так а что так зацепило
Andrey
Ну я правда хочу понять
Andrey
Никогда не видел чтобы структура после ошибки была частично заполнена
Andrey
По этому я не думал про ошибку вообще
Илья
а где видел?
Andrey
Выше