Why can’t we access string.len directly if a string is internally {header *ptr, len int}? #180558
Replies: 2 comments 1 reply
-
|
In many programming languages (like Go), a string is internally represented as a struct with a pointer to the data and a length, e.g., {ptr *byte, len int}. However, you cannot access string.len directly for a few important reasons: Encapsulation / Abstraction: The language designers want the internal representation to be hidden. Exposing len directly would tie your code to the implementation details, which might change in future versions. By using a function like len(s) instead, the language can safely change the internal layout without breaking existing code. Immutability and safety: Strings are often immutable. Allowing direct access to len might tempt someone to modify it, which could lead to memory corruption or inconsistencies with the actual data. Uniformity and flexibility: Providing a function (len(s)) lets the language implement additional checks or optimizations behind the scenes. For example, some languages may optimize string storage differently (small string optimizations, rope strings, etc.), and len(s) abstracts that complexity. |
Beta Was this translation helpful? Give feedback.
-
|
🕒 Discussion Activity Reminder 🕒 This Discussion has been labeled as dormant by an automated system for having no activity in the last 60 days. Please consider one the following actions: 1️⃣ Close as Out of Date: If the topic is no longer relevant, close the Discussion as 2️⃣ Provide More Information: Share additional details or context — or let the community know if you've found a solution on your own. 3️⃣ Mark a Reply as Answer: If your question has been answered by a reply, mark the most helpful reply as the solution. Note: This dormant notification will only apply to Discussions with the Thank you for helping bring this Discussion to a resolution! 💬 |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Select Topic Area
Question
Body
if a "string" is a struct of {header *ptr, len int}; why not allow the use of the var string.len
Beta Was this translation helpful? Give feedback.
All reactions