Injective Function on a Dense Set

This is a topological question that came up tangentially to some material I was working on. Suppose $X$ and $Y$ are complete metric spaces and $D$ is a dense subset of $X$. Let $f:D\mapsto Y$ be a continuous injection. Extend $f$ to a function $g:X\mapsto Y$ by continuity. Must $g$ be injective? It seems to me that the answer should be yes, but I haven't been able to prove it.

-
You may state the question starting from g. Can it happen that a continuous non-injective $g:X\to Y$ between complete metric space restrict to an injective function on a dense subset $D$? Of course it can, another example is e.g $x\mapsto x^2$ on $X=Y=\mathbb{R}$, restricting on $D$:={positive rationals and negative irrationals}. – Pietro Majer Aug 26 2011 at 13:13

Map the open unit interval to a circle minus a point, and then extend it to the closed interval.

-

Joel has completely answered the question, but let me add another example, with a bigger failure of injectivity of $g$. Let $D$ be the set of points in the plane of the form $(\frac1n,\sin n)$ for positive integers $n$. Its closure consists of $D$ plus the segment $S=\{0\}\times[-1,1]$ on the $y$-axis. The projection $(x,y)\mapsto x$ is one-to-one on $D$ but its continuous extension to the closure $D\cup S$, given by the same projection formula, is constant on $S$, i.e., on a bigger set than the set $D$ on which it's one-to-one.

There are analogous examples with the segment replaced by any complete, separable, metric space, for example, Hilbert space. And the only reason for needing the word "metric" there is because it was in the question; otherwise, there would be a Stone-Čech compactification example here.

-
 To answer your query, which I've now deleted, about getting the accent on Čech's name: on my computer (UK keyboard, Linux) it's done by typing AltGr-@ followed by C. – Tom Leinster Aug 26 2011 at 3:56 @Tom: Thanks. – Andreas Blass Aug 26 2011 at 4:50 Another similar example to this would be to use a dense subset of the plane that contains at most one point from each column. (One can even make it countable by using only rational points.) Thus, the projection map of this set to the $x$-axis is injective, but extends by continuity to the full projection map of the plane to the $x$-axis. – Joel David Hamkins Aug 26 2011 at 11:09