u/capedbaldy475

▲ 52 r/learnrust+1 crossposts

Why doesn't type inference help me here?

    let contents : Vec<char> = read_file!(file_name).chars().collect();

Why do I have to specify like the Vec<char> type annotation? I have seen this in the following case too:

let args : Vec&lt;String&gt; = std::env::args().collect();

Is this something related to .collect() method ?? I'm really confused here

reddit.com
u/capedbaldy475 — 9 days ago

Is accessing the bytes of an object in this way UB?

struct S
{
    int a,b,c;
    int* ptr;
};


void print_bytes(S* ptr)
{
    unsigned char* base = (unsigned char*)ptr;
    for(size_t i=0;i&lt;sizeof(S);i++) std::cout &lt;&lt; int(base[i]) &lt;&lt; ' ';
    std::cout &lt;&lt; '\n';
}

I was watching a talk on type punning where they used this example and the argument was something like the base pointer isnt guareneteed to be pointing to the first byte of the object and that accessing it like an array of chars is wrong because there was no array of chars there just an object of type S which honestly makes sense and doesn't at the same time. Can anyone explain whats' going on here?

https://www.youtube.com/watch?v=_qzMpk-22cc

45th minute onwards is where this example is talked about

u/capedbaldy475 — 13 days ago

Why does this constexpr code not compile? I don't understand why this should be an error

#include&lt;iostream&gt;
#include&lt;print&gt;
#include&lt;vector&gt;


struct S
{
    constexpr S(int n) : vec(n,0) {}
    constexpr auto get_vec() const {return vec;}
    std::vector&lt;int&gt; vec;
};



constexpr auto foo()
{ 
    constexpr S s(2);
// here is where the error comes which I don't understand
//‘S(2)’ is not a constant expression because it refers to a //result of ‘operator new’
//  193 |             return static_cast&lt;_Tp*&gt;(::operator       //  new(__n));
//
    constexpr auto my_vec = s.get_vec();   
    for(const auto&amp; el: my_vec)
    {
        std::cout &lt;&lt; el &lt;&lt; ' ';
    } 
    std::cout &lt;&lt; '\n';
}




int main()
{
    foo();
    return 0;
}
reddit.com
u/capedbaldy475 — 30 days ago