V: Int to string conversion

Created on 2 Oct 2019  路  6Comments  路  Source: vlang/v

For the matter of consistency, you may decide to drop int str() method in favor of explicit type conversion.

V version: 0.1.19
OS: : MacOS 10.14

What did you do?
According to documentation:

To force a different type, use type conversion: the expression T(v) converts the value v to the type T

mut n := 1
n_str = string(n)

What did you expect to see?
Successful type conversion

What did you see instead?
cannot cast int to string, use str() method instead

Bug

Most helpful comment

T(v) is casting, int.str() is not casting, but running an entire subprogram to convert the string.

All 6 comments

T(v) is casting, int.str() is not casting, but running an entire subprogram to convert the string.

From a user perspective, it seems inconsistent to me if some types can be casted and some can not, irregardless of internal implementation.

T(v) is casting, int.str() is not casting, but running an entire subprogram to convert the string.

If we want to retain this (rather disputable) difference, then there should be crystal clear rules in V for library makers how to construct APIs.

Semantically I regard casting as a default conversion between arbitrary types without thinking about compiler internals (it's the same as with intrinsics - I don't care that compiler compiled them to some specific code, because I do care just about the programming interface).

In general my very own rules for all type conversions are:

  1. if the language supports casting, then provide a default behavior using casting syntax (this default behavior is very important as it has only one goal apart from correctness - absolute maximum performance)
  2. always provide type conversion routine/method/you_name_it offering all viable features (e.g. type conversion int -> str can offer some printf-like formatting with padding etc. with reasonable performance which is still higher than calling successively several methods; it's also more readable)

T(v) is casting, int.str() is not casting, but running an entire subprogram to convert the string.

So what is the advantage to have both in place when the result is identical? That seems to go again the V-rule "do same stuff the same way"

There's only int.str() @gslicer

It works just like in Go. string(int) is a confusing cast that doesn't do what it's expected to do, and they are considering removing it:

https://github.com/golang/go/issues/3939

Good comment on that issue:

I would not expect an innocuously looking conversion to invoke an expensive number formatting routine. 
Was this page helpful?
0 / 5 - 0 ratings

Related issues

XVilka picture XVilka  路  3Comments

aurora picture aurora  路  3Comments

medvednikov picture medvednikov  路  3Comments

lobotony picture lobotony  路  3Comments

jtkirkpatrick picture jtkirkpatrick  路  3Comments