We can create a byte array ([5]byte) of fixed size.
Is there any way to create a fixed size for the string?
I know that string Max size is 2^31 - 1 and this will be the size if we create a variable of string datatype.
But I just wanted to know can we create a string of 20 bytes or 30 bytes.
Suppose if have a string of 1000 characters and user wants to get only 100 characters of string at first call.
He will create a string of 100 bytes(suppose if 1 char occupies 1 byte). Then I have to find out the size of the string(which user has created) and the pass only that many characters.
Here 100 is just an example user can create a string of size as they want.
Using slices we can do it as I mentioned in my first post itself. But I was looking to do using string. So from your link, we cannot do it with strings as they are fixed size.
I’ts more complex then this. Strings in go is by default encoded in utf8 so if you just take the first 100 bytes can you end up with an illegal string if your string contains anything but ascii (7 bit) characters. Utf-8 can represent single character with 1 up to 4 bytes (see https://en.wikipedia.org/wiki/UTF-8).
Just taking the first two bytes of the string “Räksmörgås” (shrimp sandwich in Swedish) results in an illegal string because the letter ä (a umlaut) takes two bytes. But if you convert the string to runes and pick the first 2 and convert them back to a string it will be “Rä”
Hi
This is different from my question. Here you creating a string with value. But I declare a empty string and then get the size of that.
example:
var a string
//Here the string size is 2^31-1
// I am trying to change the size of the declared string so that its declaration size will be 10bytes or 20 bytes