1

I am trying to get understanding of bytes array but encountered an error where,

contract Mytest {
> 
>     bytes[] public arr1 = [bytes("happy"), "names"];   // This line works perfectly 
>     bytes[] public arr2 = ["hello", bytes("hello")]; }  // It throws error but why??

Why I can't give strings as first place index?? why it throws error?

enter image description here

1 Answer 1

1

That's because Solidity only uses the first element to deduce the type of the other elements and cast them.

You cannot simply assign a string to a bytes array directly like that. You have to cast it to bytes first. Solidity will only check the first element and try to convert the other elements to the same type as the first, casting them like [bytes("happy"), bytes("names")] while compiling.

With ["hello", bytes("hello")] it checks the first element and sees that it cannot deduce its expected type which is suppose to be bytes.

I know that you may be wondering "But they should check the other elements to find the type I want to cast the elements and then cast the other elements with it". But there should be a standard, and their standard is to only check the first element to try to help you with casting the others. So they are helping with by doing that and not make you cast all the other elements manually.

1
  • So why it is showing same error when I try to do this: ontract Mytest { bytes public arr = "s"; bytes[] public arr1 = [bytes("happy"), "names"]; bytes[] public arr3 = [arr, "s"]; // here same error cannot deduce common type of array even the type of arr is deduced at compile time?? } Dec 13, 2022 at 17:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.