High level languages have too much going on. I miss structs
πŸ‘︎ 894
πŸ’¬︎
πŸ‘€︎ u/Fez-Ryan
πŸ“…︎ Jan 19 2022
🚨︎ report
Saving a Third of Our Memory by Re-ordering Go Struct Fields wagslane.dev/posts/go-str…
πŸ‘︎ 229
πŸ’¬︎
πŸ‘€︎ u/wagslane
πŸ“…︎ Jan 07 2022
🚨︎ report
Saving a Third of Our Memory by Re-ordering Go Struct Fields wagslane.dev/posts/go-str…
πŸ‘︎ 218
πŸ’¬︎
πŸ‘€︎ u/winvextw
πŸ“…︎ Jan 09 2022
🚨︎ report
String storage and string slice in the same struct

From what I've read (and experienced) you can't have a struct own storage and also borrow it. I would like to have a struct like

struct File<'a> {
    source: String
    symbols: HashMap<&'a str, Symbol>
    ast: ASTRoot<'a>
}

where the symbols and ast are borrowing the source String. Is there a smarter way to do what I want? Obviously I could make my own string-type that contains the offsets and lengths but it's not very ergonomic. I don't want to allocate a million tiny strings... Is this something that will work in the future?

πŸ‘︎ 33
πŸ’¬︎
πŸ‘€︎ u/christian_regin
πŸ“…︎ Jan 17 2022
🚨︎ report
Why aren’t Rust structs laid out in memory like C structs by default?

I’m curious why C style isn’t the default memory layout for structs in Rust. I imagine there’s some optimization that can be done if structs have a layout that’s opaque to the developer. Does anyone have an example of this type of optimization?

πŸ‘︎ 91
πŸ’¬︎
πŸ‘€︎ u/aunyks
πŸ“…︎ Jan 05 2022
🚨︎ report
Instantiate struct as Value or Pointer?

Hi guys

In GO is common saw code like this:

myStruct := &MyStruct{ Something: "some data" }
multableFunc(myStruct)

Above we see a reasonable code, no problem, but my question is:

why not this:

myStruct := MyStruct{ Something: "some data" }
multableFunc(&myStruct)

In that last example, I instantiate a value and pass the reference only into functions that need a pointer that probably will change the myStruct, at least should.

This is some style guide or just a programmer preference?

πŸ‘︎ 45
πŸ’¬︎
πŸ‘€︎ u/atomichemp
πŸ“…︎ Jan 19 2022
🚨︎ report
struct supremacy
πŸ‘︎ 113
πŸ’¬︎
πŸ“…︎ Jan 13 2022
🚨︎ report
Class vs Struct

Hi everyone,

As the title says, I have a bit of a dilemma when choosing between a struct and a class. In the object my API is returning, let's call it DeviceInfo, there is a number of properties, the majority of an integer type. Wrapping those instructs is an easy decision (https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/choosing-between-class-and-struct).

However, I have a couple of properties that are string-based (e.g. DeviceId). And I'd like to wrap them so that I do not pass strings around and do not just expose those through my public API. What would you choose for wrapping strings like these? Struct or a Class and why?

P.S. I am a bit limited on which properties do I expose as my lib is wrapping some native API.

Thanks in advance!

Edit 01: I saw the notification about a comment on this thread but for some reason, the comment itself is not there. I read a bit of the comment from the notification and understood that I did not phrase my post as I should have.

I understood that the commenter thought that I want to wrap multiple properties/strings into one type, but the point is, I want to wrap individual strings into individual types, to avoid "primitive bias" if I may call it that.

Example:

Original:

public sealed class DeviceInfo
{ 
    public string Name { get; } 
    public int Category { get; } 
}

What I'd like:

public sealed class DeviceInfo
{
    public DeviceName Name { get; }
    public DeviceCategory Category { get; }
}

And the question is, should DeviceName be a class or a struct? Probably not the most critical question, but I'd like to know a thought process behind making such a decision, in this particular case (wrapping a string).

πŸ‘︎ 18
πŸ’¬︎
πŸ‘€︎ u/Ok-Soft8210
πŸ“…︎ Jan 01 2022
🚨︎ report
Is there away to designate another property of a struct to serve as the "id" for Identifiable?

I'm working with a framework that I'm not wanting to refactor. The framework has some structs that have unique id's, but none of the props are called "id".

I need/want to use arrays of those structs in SwiftUI, and I think that I need to have them to conform to Identifiable in order to use ForEach. Can I somehow get ForEach to "point" to one of the other properties?

πŸ‘︎ 14
πŸ’¬︎
πŸ‘€︎ u/minuteman_d
πŸ“…︎ Jan 14 2022
🚨︎ report
How can a function create and return a self-referential struct
struct Data {
    number: u32,
}

struct SelfReferential<'a> {
    data: Data,
    pointer: &'a Data,
}

fn create_self_referential_struct() -> SelfReferential<'?> {
  // How can this function create an instance of SelfReferential
  // with pointer pointed to its own field
}

fn main() {
    println!("Hello, world!");
}
πŸ‘︎ 13
πŸ’¬︎
πŸ‘€︎ u/flay-otters
πŸ“…︎ Jan 17 2022
🚨︎ report
Releasing my C++ struct-of-arrays / hashtable library - critique needed!

I developed this pair of useful classes a few years back in order to help me out in my own game engine, and it might be helpful in yours. While they are tested and functional, I haven't stress-tested them to extremes or compared their performance to that of similar solutions, so I'm looking for some feedback from people who might know more about this particular subject than myself.

soa.hpp is a struct-of-arrays template container, designed to have a similar interface to std::vector. Details about how it works are in the readme and can be gleamed from the comments in the file itself.

htable.hpp is a hashtable that builds upon soa. The hash map itself is just a lightweight array of indices adjacent to the actual keys and data, so the actual table that you care about can be tightly-packed in memory and even sorted if you need it to be. This container is especially useful for an ECS engine such as my own, where a component table can literally just be an htable, using entity IDs to look up specific entries, and iterating over each entry in an elegant manner.

Again, these classes are functional and useful, but I can't claim with certainty that they're as good or better than other solutions that already exist. I would really appreciate any criticisms about any mistakes I may have missed, features I may not have considered, or any performance considerations that may have neglected. In particular, it doesn't support a custom memory allocator, and I'm not actually sure how I'd even go about enabling support for that.

You can find the code and documentation here: https://github.com/HaydnVH/soa-htable

πŸ‘︎ 25
πŸ’¬︎
πŸ‘€︎ u/Haydn_V
πŸ“…︎ Dec 31 2021
🚨︎ report
Checking if a struct implemented an option trait method

Hi everyone! I'm working on a C-rust interface, and (I think) I need to check if a particular struct implements a method.

For context, I need to give that kind of struct to the C code:

#[repr(C)]
pub struct CMethods {
    pub methodA: Option<fn(*mut c_void) -> i32>,
    pub priv: *mut c_void,
}

The C layer will then check if methodA has been implemented and if so, call it with priv as an argument. Of course there are more than one method, but I'm oversimplifying for clarity.

Now, I would like for the rust code to only have to provide a struct an implementation of Method and I could do the rust->C translation. Basically, what I'm aiming for:

trait Methods {
    methodA(*mut c_void) -> i32 { 0 }
}

// CustomType1 doesn't implement methodA
struct CustomType1 {}
impl Method for CustomType1 {}

// CustomType2 does
struct CustomType2 {}
impl Method for CustomType2 {
    methodA(*mut c_void) -> i32 { 42 }
}

fn rust_to_c<T: Method>(t: T) -> CMethods {
    CMethods {
        priv: Box::new(t),
        // here, that's the test I don't know how to write:
        methodA: if T::methodA.is_the_default_impl() {
                     None
                 } else {
                     Some(T::MethodA)
                 }.
    }
}

Is that possible?

edit: grammar

πŸ‘︎ 7
πŸ’¬︎
πŸ‘€︎ u/gquintard_
πŸ“…︎ Jan 16 2022
🚨︎ report
"Use structs sparingly, do NOT use it for organizing code. (...) Instead write more local functions and vars." reddit.com/r/golang/comme…
πŸ‘︎ 111
πŸ’¬︎
πŸ‘€︎ u/oilaba
πŸ“…︎ Dec 26 2021
🚨︎ report
self_macro: A macro to get the enclosing struct type without naming it

<https://github.com/MitalAshok/self_macro/>

I have created a library that defines a macro that can do this:

struct struct_name {
  SELF_MACRO_GET_SELF(type_alias_name, public);
  static_assert(std::is_same_v&lt;type_alias_name, struct_name&gt;);
};

This is useful in that SELF_MACRO_GET_SELF doesn't need to name the type it is in to do its work. It can be used inside other macros that generate static member functions and need access to the type itself.

As a side effect, it also exposes a global type-to-type map, with self_macro::store&lt;A, B&gt;() mapping A to B, and self_macro::retrieve&lt;A&gt; retrieving B: <https://godbolt.org/z/1Y315eGjo>. This mapping is modifiable at compile time, so might have some cool use cases.

πŸ‘︎ 55
πŸ’¬︎
πŸ‘€︎ u/MitalAshok
πŸ“…︎ Jan 12 2022
🚨︎ report
Tabled [v0.4.0] - An easy to use library for pretty print tables of Rust structs and enums.

https://github.com/zhiburt/tabled

There is a list of main additions.

  • Highlight modifier which does highlight of any combination of cells.
  • Concat modifier which does concatenation of two tables into one.
  • TableIteratorExt trait which can be used to create table from `Iterator`.

An example bellow shows usage of each of these features.

use tabled::{Border, Concat, Highlight, Style, TableIteratorExt};

fn main() {
    let data = vec[["A", "B", "C"], ["D", "E", "F"], ["G", "H", "I"]];

    let table = (0..data.len())
        .table()
        .with(Concat::horizontal(data.table()))
        .with(Style::PSEUDO)
        .with(Highlight::cell(
            2,
            2,
            Border::full('*', '*', '*', '*', '*', '*', '*', '*'),
        ));

    println!("{}", table);
}

The printed result.

β”Œβ”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”¬β”€β”€β”€β”¬β”€β”€β”€β”
β”‚ usize β”‚ 0 β”‚ 1 β”‚ 2 β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”Όβ”€β”€β”€β”Όβ”€β”€β”€β”€
β”‚   0   β”‚ A β”‚ B β”‚ C β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€*****────
β”‚   1   β”‚ D * E * F β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€*****────
β”‚   2   β”‚ G β”‚ H β”‚ I β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”΄β”€β”€β”€β”΄β”€β”€β”€β”˜
πŸ‘︎ 35
πŸ’¬︎
πŸ‘€︎ u/zhiburt
πŸ“…︎ Dec 30 2021
🚨︎ report
What if Rust allowed `typeof` operator for creating type aliases (for struct fields)?

Context: https://github.com/rtic-rs/cortex-m-rtic/issues/574

So, the issue I am facing is that there is a library RTIC that generates certain structs in a way that the whole struct is public, I can reference this struct by its name, its fields are public, too. They provide some public API. I can have ownership of that struct.

However, types of some of its fields are hidden (they are public, but they reside in private modules).

This creates situation where I can do pretty much everything with the struct. For example, I can deconstruct it (take the field out of the struct and put them in local variables, for example).

What I cannot do is to declare the type of these fields. I cannot create my own struct that declares some of those fields and move them into it. I cannot create my local variable with an explicit type (but type inference works).

This made me thinking, what are the benefits of not being able to name some type if I can still capture that type via type parameters? For example, I can do var x = Some(outer.field), and type will be (implicitly) part of the Option&lt;T&gt; type. Or I can declare a function that captures that type in a type parameter.

What if Rust provided a way to create type alias for a struct field? Something like typeof Outer::field? For example, for local variable I could write let x: typeof Outer::field.

What would it allow to do what library authors don't want me to? Well, I mean, obviously, they don't want me to reference their types by name, but why that would be bad? Like, what kind of additional API burden would it place on library authors? What kind of type (API?) safety would be compromised?

πŸ‘︎ 19
πŸ’¬︎
πŸ‘€︎ u/idubrov
πŸ“…︎ Jan 07 2022
🚨︎ report
Iterating over vectors with structs - what's the point?

Hi,

Many examples in the Rust documentation use iterators to loop over vectors. However in practice Ive run into many situations where I seem to be forced to revert to index based loops. I've begun wondering whether there's something I'm missing?

what I mean is that this:

for item in vector {}

seems not to be sufficient in many cases, forcing me to use this instead:

for i in 0..vector.len() {
vector[i]
}

By the way, I get why its not allowed. Here's what I'm running into:

- You can't modify either the vector, or the elements in the vector. (Isn't this often the point of iteration? To modify whatever you're looping over)

- Iterator functions seem complex (there are a lot of different ones, and figuring out what does what is not trivial. They are not always consistent across different crates)

- If you have a parallel array that keeps temporary data related to the vector items, then you need the index for synchronisation reasons

So am I missing something here?

πŸ‘︎ 6
πŸ’¬︎
πŸ‘€︎ u/garma87
πŸ“…︎ Jan 14 2022
🚨︎ report
How do structs work internally?

How do structs work internally in memory. I know that an instance of a struct is a pointer to the first field of the struct. I also know that all the fields of a struct are contiguous to each other in memory so the memory address of the second field of a struct can be accessed by adding the size of the first field to the memory address address of the first field.

I am failing to understand that how do we access the consequent fields of a struct with just the memory address of the first field. We can do it in arrays by jumping x bits ahead according to the data type of the array, we can only do this in arrays because the values in a certain array have the same data type. My question is that how do we navigate through the fields of a struct by only knowing the memory address of the first field of the struct.

Thanks!

πŸ‘︎ 70
πŸ’¬︎
πŸ‘€︎ u/hamiecod
πŸ“…︎ Dec 18 2021
🚨︎ report
Adding generics defeated the objective to have a "strongly typed" language. Developers like me will use any instead of defining a struct. old.reddit.com/r/golang/c…
πŸ‘︎ 113
πŸ’¬︎
πŸ‘€︎ u/cmov
πŸ“…︎ Dec 20 2021
🚨︎ report
Style/Pattern for Go Database, DTO& Validation Struct

I'm creating a web server (Internet facing) to be consumed by a JavaScript frontend, and am using Chi as the web framework and Gorm as the ORM, with Postgres as the database.

I'm now looking at creation of struct, and am wondering what's the proper style/pattern for creating struct for my models/DTO.

E.g. If there's a Human model, should I declare Human and HumanDTO separately, or use a common struct? (You may also see that I've added the additional circumstance that Age should be in DB but not JSON, while Height should be in DTO but not DB)

Approach 1: Single Declaration

type Human struct {
    Name   string `gorm:"index" json:"name" validate:"required"`
    Gender string `gorm:"index" json:"name" validate:"required"`
    Age    int    `gorm:"index" json:"-"`
    Height int    `gorm:"-" json:"height" validate:"required"`
}

Approach 2: Separate Declaration

type Human struct {
    Name   string `gorm:"index"`
    Gender string `gorm:"index"`
    Age    int    `gorm:"index"`
}

type HumanDTO Struct {
    Name   string `json:"name" validate:"required"`
    Gender string `json:"name" validate:"required"`
    Height int    `json:"height" validate:"required"`
}

Are there any tradeoffs I'm making that I should be aware of, or any potential pitfalls?

Also, it's also likely I'll need to create other structs for input, etc, as they might be different. Would this also impact the above decision?

πŸ‘︎ 11
πŸ’¬︎
πŸ‘€︎ u/telboon
πŸ“…︎ Jan 09 2022
🚨︎ report
Is there a way to append to struct in Rust?

Is there a feature to create a new struct by copying existing struct and appending some members to it. (something like the include keyword in Ocaml modules)

πŸ‘︎ 23
πŸ’¬︎
πŸ‘€︎ u/cola-Bear
πŸ“…︎ Dec 24 2021
🚨︎ report
global and local structs

i am currently using typedefs to create better names for structs/unions which i think are the best places to use typedefs as ive seen examples of people typedef 'ing' and int type which i see as pointless. below i create a struct of type struct employee and create an ALIAS type name as EMPLOYEE. However when i create an instance of this struct outside main and any other func hence it has global scope(ie:right at the top the c file). However, it does not allow the members of the struct to be specified whereas if when i specify a local struct within the main func called EMPLOYEE Manager i am able to work with the struct and specify the members. can anyone put their finger on what im missing or misunderstand.

EDIT: Essentially, i want a way for emp to be available globally and Manager to only be available locally only for the main func

typedef struct employee
{
    //struct members
    char *name; //pointer to block of mem of data type char
    int age;
    int salary;
    float HoursWorked;
}EMPLOYEE; //new type name

//block of code between emp1 declaration and main func wont work 
EMPLOYEE emp1;
emp1.age = 19;
emp.name = malloc(10) //allocates 10 char blocks totaling to 10 bytes (10*1), returns pointer to address of first mem location
emp.salary = 200;
emp.HoursWorked = 10;

int main(){
    //below runs fine when a manager struct with local scope is declared
    EMPLOYEE Manager;
    Manager.age = 45;
    Manager.name = malloc(10);
    Manager.salary = 500;
    Manager.HoursWorked = 30;

    //can work with Manager struct in this func

}
πŸ‘︎ 5
πŸ’¬︎
πŸ“…︎ Jan 14 2022
🚨︎ report
Best way to serialize / deserialize structs for network transport

Hello Everyone,

I have structs that I need to send over the network. I was just using sprintf / sscanf to convert the structs to strings and back using the same format strings, but I hit a snag:

I have a struct that has a 4kB buffer of binary data.

What would you recommend?

πŸ‘︎ 15
πŸ’¬︎
πŸ‘€︎ u/thesuperbigfrog
πŸ“…︎ Jan 06 2022
🚨︎ report
TwinCAT 3 OPC UA Client and Structs

Hi,

I need some support using TwinCAT 3 and OPC UA as a Data Source. I want to pull one byte variable from an Array of Structs as an OPC UA Client.

Browsing the Array of Structs using UaExpert looks like this. Browsing it from TwinCAT 3 as an OPC UA Client it looks like this.

You can imagine my confusion. Beckhoff's documentation on this is saying the OPC UA Client cannot recognize User Defined Structures.

I think all the data from the struct is displayed in the Byte Array.

Does anyone have a smart idea how I can extract this data easiert?

πŸ‘︎ 3
πŸ’¬︎
πŸ‘€︎ u/FelixOwnz
πŸ“…︎ Jan 17 2022
🚨︎ report
Help with CFFI, C struct decoding, best practices / portability

I've been using CFFI to access the CRoaring C API to Roaring Bitmaps. It's been pretty easy so far. However I'm not experienced in lisp FFI, and I'm unsure of the way to go about the task of decoding a C structure used for iteration in the C API. The structure is as follows:

typedef struct roaring_uint32_iterator_s {
    const roaring_bitmap_t *parent;
    int32_t container_index;         
    int32_t in_container_index;  
    int32_t run_index;           
    uint32_t current_value;
    bool has_value;

    const ROARING_CONTAINER_T
        *container;  
    uint8_t typecode;
    uint32_t highbits;
} roaring_uint32_iterator_t;

The APIs hand me a pointer to the above and mutate the structure in logical first()/last()/next()/prev() type calls.

The two members I need to access are current_value and has_value. I'm wondering the best way to do this so that the code will run on different architectures/lisps via CFFI.

πŸ‘︎ 6
πŸ’¬︎
πŸ‘€︎ u/Decweb
πŸ“…︎ Jan 15 2022
🚨︎ report
Why using struct list isn't a lot faster than using class list? Question about cache

As far as I understand struct list have these benefits over class list when using them for highly performant code blocks

  • Structs are allocated contiguously, whereas classes are all over the place in heap, so they should cause more cache misses
  • Classes have 16bytes more data in them if they had the same fields as the struct, so you can fit less of them in cache
  • Classes cause another pointer dereference, so they should evict cache more often

So I did some benchmarks about this, could share them if needed, but traversing linearly struct list over class list(both only have 1 float field) seems to have only 10% performance gain over the class. I feel like using structs should have more performance impact from reading about cache, but it doesn't apply to the benchmarks. I'm curious why.

Edit: Here's a quick sample code (I'm at work rn so I can't post the benchmark code atm)

Guys I know this isn't proper benchmark code, I have the original code on my desktop home

using System;
using System.Diagnostics;

namespace BenchmarkTest
{
    internal class Program
    {
        public static void Main(string[] args)
        {
            GC.Collect();
            var example = new ClassVsStructList();
            example.Setup();

            var sw = Stopwatch.StartNew();
            example.SumStructList();
            sw.Stop();
            
            Console.WriteLine((sw.ElapsedTicks).ToString());

            sw = Stopwatch.StartNew();
            example.SumClassList();
            sw.Stop();
            
            Console.WriteLine((sw.ElapsedTicks).ToString());
        }
    }

    public class ClassVsStructList
    {
        public class DataA
        {
            public int Value;
        }

        public struct DataB
        {
            public int Value;
        }

        public class Dummy
        {
            public int[] Value = new int[100];
        }

        private DataA[] _classArray;
        private DataB[] _structArray;

        public void Setup()
        {
            var random = new Random((int)Stopwatch.GetTimestamp());

            _classArray = new DataA[10_000_000];

            for (int i = 0; i &lt; _classArray.Length; i++)
            {
                _classArray[i] = new DataA { Value = random.Nex
... keep reading on reddit ➑

πŸ‘︎ 35
πŸ’¬︎
πŸ‘€︎ u/velen_rendlich
πŸ“…︎ Dec 07 2021
🚨︎ report
for sets: map[T]struct{} vs. map[T]bool

I recently saw a colleague using map[T]struct{} as a set of unique T.

seen := map[string]struct{}{}
for _, s := range stuff {
    if _, ok := seen[s]; !ok {
        // do stuff
        seen[s] = struct{}{}
    }
}

I personally prefer using map[T]bool like this:

seen := map[string]bool{}
for _, s := range stuff {
    if !seen[s] {
        // do stuff
        seen[s] = true
    }
}

In my opinion the bool version is a little more readable.

which do you prefer and why?

πŸ‘︎ 61
πŸ’¬︎
πŸ‘€︎ u/Potatoes_Fall
πŸ“…︎ Nov 22 2021
🚨︎ report
How to return a default struct value by reference?

Hey all!

I'm working on a Unity DOTS project that needs to make use of a blob asset. Blob data is retrieved by reference. I want to create a helper method to retrieve a memory with a matching settings index. It's possible that a matching memory will not exist, in which case it should return some sort of default value so that the calling method can know that the value returned isn't actually valid.

The problem is that I'm receiving the following error for the return at the bottom: "An expression cannot be used in this context because it may not be passed or returned by reference." I'm looking for a way to achieve something similar in a way that the compiler is okay with.

A worst case scenario would be populating the buffer with a dummy value, treating the 0th value as a stand-in for "does not exist." This would be a really ugly hack, so I'm really hoping to avoid it.

using Unity.Entities;

namespace RockMine.C4.Agents
{
    public static class MemoryBufferExtensions
    {
        public static ref MemoryData MemoryGet(
            this DynamicBuffer&lt;MemoryBufferElementData&gt; buffer,
            int memorySettingsIndex)
        {
            for(int i = 0; i &lt; buffer.Length; i++)
            {
                ref var memory = ref buffer[i].Value.Value.Memory.Value;

                if(memory.MemorySettingsIndex == memorySettingsIndex)
                {
                    return ref memory;
                }
            }

            return ref default(MemoryData);
        }
    }
}
πŸ‘︎ 11
πŸ’¬︎
πŸ‘€︎ u/EdvardDashD
πŸ“…︎ Jan 15 2022
🚨︎ report
SSLv3 ServerKeyExchange Signature struct differs from RFC6101

I'm playing with implementing SSLv3 in Go according to rfc6101.

I can deserialize ServerKeyExchange until ServerKeyExchange.signed_params.

The cipher suite is TLS_RSA_EXPORT_WITH_RC4_40_MD5 (0x0003).

The Certificate signature algo: 1.2.840.113549.1.1.5 (sha1WithRSAEncryption).

According to the RFC the structs should look like this:

    struct {
            select (KeyExchangeAlgorithm) {
                case diffie_hellman:
                    ServerDHParams params;
                    Signature signed_params;
                case rsa:
                    ServerRSAParams params;
                    Signature signed_params;
                case fortezza_kea:
                    ServerFortezzaParams params;
            };
        } ServerKeyExchange;

        digitally-signed struct {
            select(SignatureAlgorithm) {
                case anonymous: struct { };
                case rsa:
                    opaque md5_hash[16];
                    opaque sha_hash[20];
                case dsa:
                    opaque sha_hash[20];
            };
        } Signature;

but i got a different response form the server:

Wireshark capture

What i am missing?

Thanks!

πŸ‘︎ 18
πŸ’¬︎
πŸ‘€︎ u/g0rbe
πŸ“…︎ Jan 02 2022
🚨︎ report
Are structs and pointers to them deep-copied by default?

I have an application in which there're many structs with nested structs, pointers to them, and just values as well. I've noticied some mistakes in calculations, but haven't been able to identify a cause. I suspect that that it might be that some data is lost due to the fact, possibly, that structs aren't deeply copied **by default** in Go.

Is that case? Are structs and pointers to them deep-copied by default? Where is that described?

upd1:

There're a lot of assignments of structs, and their nested fields, to variables, and updating fields by assigning them to variables, in the code.

upd2:

I don't know if I want is deep copy. Say, I have struct S1 which contains nested, of multiple levels, non-trivial data types - other structs, maps, pointers... as well as trivial types. Each field has some data in it.

Say, there're s1AsVar (variable) and s1AsPtr (pointer) . Then, there're also additional 2 variables:

  a1 := s1AsVar //1
  a2 := s1AsPtr //2

Would the nested fields with all their data, however nested, be copied correctly and completely into a1 and a2?

In other words, would I be able to access all data from a1 and a2?

πŸ‘︎ 6
πŸ’¬︎
πŸ‘€︎ u/Usual_Stay_3812
πŸ“…︎ Dec 30 2021
🚨︎ report
Scanning joined SQL rows into nested go struct

Let's say I have a struct such as:

type Person struct {
	ID uint32
	Name string
        // .. other fields of Person
	Pet []Pet
	Company Company;
}
Type Company struct {
	ID uint32
	Name string
        // ... other fields of Company
}
type Pet struct {
	ID uint32
	Name string
        // ... other fields of Pet
}

The SQL I would use in such a case is something like:

SELECT person.*,company.*,pet.* FROM person
-- join with company 
JOIN person_company  ON person_company.person_id=person.id 
JOIN company ON company.id=person_company.company_id
 -- join with person 
JOIN person_pets ps ON person_pets.person_id=person.id 
JOIN pet ON pet.id=person_pets.pet_id

ORDER BY person.id, company.id, pet.id;

I was thinking of doing something like:

  1. Scan row by row
  2. When seeing a new person.id, create an instance of it, and add the previous instance to the result list
  3. When seeing a new company.id for this person.id, add it to person
  4. When seeing a new pet.id for this person add it to the pet.

I was wondering if this is the best way. And if there are any clean code examples of this?

πŸ‘︎ 6
πŸ’¬︎
πŸ‘€︎ u/aclokay
πŸ“…︎ Jan 02 2022
🚨︎ report
Code testability and functions vs structs

This post is my question about how to structure Rust code for testability. And, is it possible to do it in a way that avoids boilerplate code.

First of all, I come from .NET background. I am used to the fact that everything is a class. Even a small utility function that is two lines long, and doesn't contain any state has to be a part of a class (maybe a static one).

In Rust, at first, I loved the idea that functions can be "free" - they don't have to be defined in classes. It's very close to what JavaScript offers. I can group functions that have similar "theme" in a file (e.g. I could have a file file_utils.rs that has a bunch of functions related to file operations. Such a file becomes a module and I can treat that module a bit like a static class (without the need to write the static class {...} boilerplate. That's nice.

However, I started to feel a bit confused when I wanted to write unit tests for my code. I have a bunch of functions, they operate on some files, but I want to be able to control which files they operate on in testing functions. Here's a small example:

pub fn is_associated(path: &amp;Path) -&gt; Result&lt;bool, Box&lt;dyn Error&gt;&gt; {
    let config = AppConfigManager::new()?.get_config()?;
    if config.projects.iter().any(|p| p.path == path) {
        return Ok(true);
    }

    Ok(false)
}

It doesn't matter what this function does exactly. The important thing is that it creates some instance of some struct called AppConfigManager and retrieves some data for it. The problem is that AppConfigManager retrieves that config file from a hardcoded location that is valid when I run my app with cargo run. I want to use a different location for tests.

I could probably do the following:

  1. Create some trait ConfigManager with a method get_config().
  2. Modify AppConfigManager to implement that trait.
  3. Modify my function is_associated() to accept a trait object ConfigManager as one of its inputs and use that object to get the config.
  4. Write a test where I have some MockConfigManager and I would pass it to my function.

I don't like that approach, because the function's signature becomes too "noisy". I am not a fan of dependency injection via function parameters.

So, I started to think that in order to have testable code and nice function signatures I will have to go the C# way:

  1. Create structs for my functions (first I'd group them to have a few functions per struct)
  2. Each struct would implem
... keep reading on reddit ➑

πŸ‘︎ 5
πŸ’¬︎
πŸ‘€︎ u/Loreno10
πŸ“…︎ Jan 11 2022
🚨︎ report
How do I unmarshal JSON API responses into a struct if I can't be sure the API won't change

Our team is looking to read JSON payloads from Microsoft Graph API. We've created some structs that replicate all of the fields that Microsoft's documentation states a given response might contain as sadly Microsoft do not have a Golang package that has pre-made and supported structs.

In theory, Microsoft never changes the API, but we all know reality doesn't always work this way.

Say, one day Microsoft adds an additional field to the JSON response, then suddenly our code blows up as soon as we try to unmarshal this into the structs we've created because it has an additional unexpected field.

How do we make this safe for production code? Frankly, we don't trust microsoft to not blow up our production code because they added an extra field to their API at 3am one day.

This must be a problem others have faced before. If we were writing our project in another language (eg: python) it's possible to read arbitrary JSON into dictionaries. Is there a nice pattern for having a struct that forgives additional/unexpected fields in Go?

πŸ‘︎ 8
πŸ’¬︎
πŸ‘€︎ u/Arbortheus
πŸ“…︎ Dec 14 2021
🚨︎ report
Is there a way to reinterpret_cast same struct with different names? And especially vectors for the structs?

So I have library_xy gives me std::vector&lt;xy&gt; at some point, and I want to pass result to library_XY, but it accepts only std::vector&lt;XY&gt;. Structs are struct xy{float x, float y; void f1(){}}; and struct XY{float X, float Y; void f2(){}};

I'm pretty sure that all arch-OS pairs will align the structure exactly the same, yet there is no standard-complaint way I know to just say "this is really the same vectors, trust me".

This "works on my machine":

std::vector&lt;xy&gt; in = get_xy();
std::vector&lt;XY&gt; out;

memcpy(&amp;out, &amp;in, sizeof(in));
memset(in, 0, sizeof(in)); // Destructor, no destructing!

sendXY(out);

And this is robot-unicorn level UB and extremely implementation-dependent.

The only way I know to create vector of XY from vector of xy is to manually construct them all, something like

for(auto const &amp;val : in) { out.push_back({val.x, val.y}); }

This may never be a bottleneck, but it just doesn't feel right to copy megabytes of date for no good reason.

Is there some way to tell a compiler, that these two completely different types are exactly the same. Like, temporary disabling strict aliasing for a specific function and just do something like

std::vector&lt;XY&gt; &amp;out = *reinterpret_cast&lt;std::vector&lt;XY&gt;*&gt;(&amp;in);

or maybe

union XYxy{
    std::vector&lt;xy&gt; *in;
    std::vector&lt;XY&gt; *out;
};

or any way at all?

EDIT: So, 5 days later, we've got this:

  1. Nope, not possible according to current C++20 standard
  2. But! It looks like even `reinterpret_cast<vector<B>*>(&vector_A_obj)` works in practice at least for some compilers.
  3. Also! We have a proposal to safely alias any structs like struct {int v1, int not_v1, int v3, int r}; to int[4];: Types with array-like object representations. Fingers crossed on this one.
πŸ‘︎ 51
πŸ’¬︎
πŸ‘€︎ u/topin89
πŸ“…︎ Nov 12 2021
🚨︎ report
Struct switch-indexing with 20 values faster than using array?? (GLSL)

Context: Using the stupidStack with the getStack and setStack instead of indexing the stack array like a normal human being made my compute shader run 25% faster.

The int array can be declared before or inside of the main(), it doesn't matter.

Am I doing something wrong with my int array?

https://preview.redd.it/tunw8nxi1ca81.png?width=355&format=png&auto=webp&s=dfb761c02571f584ab215f20bc84d1abbe7c3ee9

Even more context for clarity: This code is part of a firstHit shader in a ray tracer. It traverses a BVH, keeping track of far nodes that need to be traversed later by pushing them onto the stack. For 99+ percent of the rays, the stack never grows bigger than 10 integers. More than half don't ever even grow past 6 ints.

πŸ‘︎ 9
πŸ’¬︎
πŸ‘€︎ u/augustvc5
πŸ“…︎ Jan 07 2022
🚨︎ report
How to distinguish an empty struct from the one with the fields equal to the default values which have been calculated and turned out to be 0, "" or false?

I have a custom struct with primitive types in it, and a function which returns the struct, by value.

I need a way for the function to signal that "this time I'm returning actual nil or empty value, and not a struct with the fields that've been initialized with default values".

Likewise, I also want to return a struct with the fields which values are equal to actual default values of the primive types: 0, "", false.

And I need a way to distinguish between the two. This would be similar to Option monad.

How to do this in an idiomatic and simple way? Should I return a pointer instead of a value?
Without any additional library.

πŸ‘︎ 3
πŸ’¬︎
πŸ‘€︎ u/Usual_Stay_3812
πŸ“…︎ Jan 02 2022
🚨︎ report
Get size of struct from static member variable.

Trying to do something like this

struct A
{
    static const int SIZE = sizeof(A);
    int otherVariables;
}

How can I make this work?

Compiler says "incomplete type not allowed" for the sizeof(A)

πŸ‘︎ 7
πŸ’¬︎
πŸ‘€︎ u/dukey
πŸ“…︎ Dec 21 2021
🚨︎ report
Generally, when do you expose structs' members?

I'm learning Go coming from a Java background and what I'm still getting used to is when to expose a struct's members. It seems not uncommon in Go to expose (some of) a structs' fields without keeping it behind a getter/setter.

How do you generally approach this? When (if ever) do you expose these fields?

πŸ‘︎ 12
πŸ’¬︎
πŸ‘€︎ u/Forumpy
πŸ“…︎ Dec 11 2021
🚨︎ report
Single Function Parameter for Multiple Struct Types?

Let's say that I have two structs,

typedef struct {
    i32 x;
    i32 y;
} sa;

typedef struct {
    u32 x;
    u32 y;
} sb;

As you can see, the member names are the same, but the types are different. Is there a way that I can create a parameter to a function that can accept either of these structs?

Edit: I forgot to add, I'd like to do this without making the function a macro.

πŸ‘︎ 12
πŸ’¬︎
πŸ‘€︎ u/TheEmeraldFalcon
πŸ“…︎ Dec 21 2021
🚨︎ report
When using the builder pattern, should the intermediate representation be the same type as the final struct?

I have a question regarding the types to use when using the builder pattern. Should the final struct be a different type than the struct while it's being built? Something like an IncompleteThing that eventually becomes a Thing when built? My thinking is that a struct could be in an incomplete state until all the required builder methods are called and parameters are supplied. Or is there a better way to ensure that a struct is always in a valid state even while being built?

πŸ‘︎ 35
πŸ’¬︎
πŸ‘€︎ u/russmbiz
πŸ“…︎ Nov 27 2021
🚨︎ report
How large should a struct be before you should pass by reference for performance?

An application I'm working on uses the golangci-lint tool to run it's static analysis. I've hit an issue where the gocritic linter complains that a struct that I'm passing by value is too large (~120 bytes) and I should pass by reference instead.

The gocritic default for this rule is set to 80 which feels aggressively conservative to me.

I'm trying to follow a value first approach, and in this case the function does not mutate the struct, so passing it by value makes sense. I do have the ability to modify the rule from the default, but I will need to justify the change. The problem is I'm struggling to find much guidance on what a sensible value would be (or indeed if the default of 80 actually is a sensible value?). Can anyone provide some recommendations or guidelines?

For context, this application is a SaaS application that is fairly high level, so I think code semantics (passing by value when you don't need a pointer) takes priority over small differences in performance. I've also profiled the application and our bottleneck is i/o (gRPC requests and database driver) by a significant margin, so I'm not overly concerned about copying slightly larger structs.

πŸ‘︎ 27
πŸ’¬︎
πŸ‘€︎ u/Exeson
πŸ“…︎ Dec 09 2021
🚨︎ report
Single struct multiple serde strategies

Is it possible to have a single Struct that can have different strategies for serialization/de-serialization? For example if I wanted to use the field rename attribute to rename the same field with different renames per serialization (Serialize to JSON with rename="foo", Serialize to BSON with rename="bar"). I could create two separate Structs but I suspect there must be a better way.

πŸ‘︎ 6
πŸ’¬︎
πŸ‘€︎ u/roberts_d
πŸ“…︎ Jan 11 2022
🚨︎ report

Please note that this site uses cookies to personalise content and adverts, to provide social media features, and to analyse web traffic. Click here for more information.