Canonical divisor on algebraic curve

Can someone help me with this problem?

Let $D$ be a divisor on an algebraic curve $X$ of genus $g$, such that $\deg D = 2g-2$ and $\dim L(D) = g$. Then $D$ must be a canonical divisor.

By Riemann-Roch, I see that $\dim L(K-D) = 1$ for any canonical divisor $K$, as must certainly be the case. I don’t know if this is too helpful.

Solutions Collecting From Web of "Canonical divisor on algebraic curve"

A divisor of degree $0$ and dimension $1$ is principal.
Hence by assumption and Riemann-Roch the divisor $K-D$ is principal,
so that $D$ is linearly equivalent to the canonical divisor $K$.

In “Algebraic Curves” by Fulton, p.212/213 it is shown that $l(K-D)$ equals
the dimension of $\{ \omega\in \Omega : {\rm div} (\omega)>D\}$.
In our case this dimension equals 1. Hence there exists a non-zero differential
$\theta$ with ${\rm div}(\theta)>D$. But ${\rm div}(\theta)$ and $D$ have the
same degree, namely $2g-2$. It follows that ${\rm div}(\theta)=D$ and $D$ is
a canonical divisor.