Check out what the science says about losing and gaining muscle while trying to lose weight.
Can you build muscle whilst in a calorie deficit? And the answer to that is actually yes, you can. This was actually studied in 2016 by "Longland et al". What they did was they separated 40 men into two groups. They immediately put both groups into a 40% energy deficit.
Group one was fed 1.2 grams of protein per kilo of body weight. Whilst the second group was fed 2.4 grams of protein per kilo of body weight. They then both completed the same six week block of resistance training And all the meals they were given were pre planned by the nutrition research group so no one can cheat at all.
So what they found was that over the six week course both groups were able to build muscle whilst being in an energy deficit. Now obviously the group that was fed more protein throughout the process were able to build more muscle. But the takeaway points of this are that if you are in a calorie deficit then you don't need to worry about losing muscle mass throughout the process.
Obviously the main takeaway point I think is that you need to make sure that your protein is set to about 2 grams per kilo of body weight. But it also means that you could go as low as 1.2 grams per kilo of body weight and still not lose any muscle mass.