Append! to an Int array with string (bug?)

I was messing around in the REPL with append! and noticed the following behavior:

julia> a1 = [1,2,3]
3-element Array{Int64,1}:
 1
 2
 3

julia> append!(a1, "AAAA")
7-element Array{Int64,1}:
  1
  2
  3
 65
 65
 65
 65

While I understand what is going on here (the string “AAAA” is being treated as an array of Char like in C), is this the expected behavior for Julia? I would’ve expected to either get an error because of incompatible types or promotion of the a1 array to Any, but I wasn’t expecting that the string would be treated as an array of chars.

1 Like
julia> @edit append!(a1, "AAAA")

shows that it is calling the append! method for an iterable, and indeed iterating through a String does the following:

julia> for i in "AAAA"
       @show i, typeof(i)
       end
(i, typeof(i)) = ('A', Char)
(i, typeof(i)) = ('A', Char)
(i, typeof(i)) = ('A', Char)
(i, typeof(i)) = ('A', Char)
1 Like

Thanks for confirming the behavior. My real question is whether it should behave this way? Do we treat strings as Arrays of Chars elsewhere?

That string isn’t treated as an Array{Char} there, but as any iterable:

append!([1,2,3], ('a' for i in 1:3))

It is a little surprising to me that a Char gets automatically converted to an Int here. This seems potentially dangerous in this particular case, though I haven’t thought through the broader implications of this.

1 Like

Sorry for the mistake in nomenclature, but @ExpandingMan is getting at my surprise/question. Have the iterable be decomposed into Chars, and the Chars converted into Int to work with the main array seems odd (rather than having an error).

This is pretty unfortunate but I think it’s a fairly unavoidable consequence of strings being iterable sequences of characters and the fact that Char is convertible to Int. However, @jeff.bezanson is working on a change for 0.7/1.0 which will allow Int('x') to work while convert(Int, c::Char) need not be allowed, which would fix this issue.

8 Likes